web-dev-qa-db-fra.com

Comment initier correctement une UITableviewCell personnalisée?

J'utilise les 2 méthodes suivantes pour renvoyer une cellule personnalisée:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *key = [self keyForIndexPath:indexPath];
    UITableViewCell *cell;

    if ([key isEqualToString:DoneButtonCellKey]) {
        cell = [self [self doneButtonCellForIndexPath:indexPath];
        return cell;
    } else {
        //code to return default cell...
    }
} 

Ensuite:

- (DoneButtonCell *)doneButtonCellForIndexPath: (NSIndexPath *)indexPath {

    DoneButtonCell *cell = [self.tableView dequeueReusableCellWithIdentifier:DoneButtonCellIdentifier forIndexPath:indexPath];
    return cell;

}

Quelle est la bonne méthode d'initialisation à utiliser avec la cellule ici afin que je puisse modifier certaines propriétés de la cellule lors de son initialisation?

EDIT: J'ai trouvé le problème, car les méthodes init/awakeFromNib n'étaient pas appelées pour moi. J'ai retrouvé l'erreur et c'est que je n'avais pas changé la "classe personnalisée" de UITableViewCell en ma classe personnalisée. Maintenant, awakeFromNib ET initWithCoder fonctionnent comme décrit ci-dessous.

29
Michael Campsall

Vous pouvez faire vos changements dans la classe DoneButtonCell, soit dans le

- (void)awakeFromNib
{
 .. essential to call super ..
 super.awakeFromNib()
 //Changes done directly here, we have an object
}

Ou la initWithCoder: méthode:

-(id)initWithCoder:(NSCoder*)aDecoder
{
   self = [super initWithCoder:aDecoder];

   if(self)
   {
     //Changes here after init'ing self
   }

   return self;
}
36
Mostafa Berg

Si vous utilisez Swift, n'oubliez pas que la manière la plus simple de s'assurer qu'une vue est initialisée lors de sa création est d'utiliser la méthode didSet. Par exemple, pour transformer un UIImageView en une forme ronde, vous pouvez ajouter du code comme ceci:

@IBOutlet weak var profileImageView: UIImageView! {
    didSet {
        // Make the profile icon circle.
        profileImageView.layer.cornerRadius = self.profileImageView.frame.size.width / 2
        profileImageView.clipsToBounds = true
    }
}
5
TALE

Voici comment j'initialise des cellules personnalisées

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"FileTableViewCell";

    FileTableViewCell *cell = (FileTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FileTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    // Configure the cell here...
      // Configure the cell.
FileRepresentation* fileRepresentation = _fileList[indexPath.row];
cell.textLabel.text = [self userFilename:[fileRepresentation.fileName stringByDeletingPathExtension]];

cell.detailTextLabel.text = [fileRepresentation modifiedDate];


cell.accessoryView=nil;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
[cell.progressIndicator setHidden:YES];

cell.imageView.image = [UIImage imageNamed:_fileImageName];

// Disable any user interaction while processing a request
if (_fileIsOpen || _creatingDocument || _deletingDocument) {

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.textColor = [UIColor grayColor];

} else {

    cell.textLabel.textColor = [UIColor blackColor];
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;

}

}
3
Duncan Groenewald
  1. Essayez d'abord de retirer de la file d'attente une cellule si possible en utilisant la méthode dequeueReusableCellWithIdentifier de UITableView.
  2. Si la cellule n'est pas disponible (nil) utilisez [[NSBundle mainBundle] loadNibNamed:@"<#your custom cell nib name#>" owner:nil options:nil][0] pour l'initialiser.
  3. Dans le fichier .m de votre cellule personnalisée, implémentez initWithCoder: initialiseur pour le code d'initialisation personnalisé:

- (id)initWithCoder:(NSCoder *)aDecoder {  
    self = [super initWithCoder:aDecoder];  
    //your custom initialization code  
    return self;  
}  

Il s'agit de l'initialiseur désigné qui est appelé lorsqu'une vue est chargée à partir d'une pointe avec loadNibNamed, comme une cellule de vue de table personnalisée.

1
Ayan Sengupta