Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use "viewWithTag" with "dequeueReusableCellWithIdentifier"?

can someone please explain why you should use viewWithTag to get subviews (e.g. UILabel etc) from a cell in dequeueReusableCellWithIdentifier?

Some background info: I've got a custom UITableViewCell with a couple of UILabels in it (I've reproduced a simple version of this below). These labels are defined in the associated NIB file and are declared with IBOutlets and linked back to the custom cell's controller class. In the tableview's dequeueReusableCellWithIdentifier, I'm doing this:

CustomCell *customCell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:@"CustomCellId"];
if (customCell == nil) {
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"customCell" owner:self options:nil];
    for (id oneObject in nib)
        if ([oneObject isKindOfClass:[CustomCell class]])
            customCell = (CustomCell *)oneObject;
}

customCell.firstLabel.text = @"Hello";
customCell.secondLabel.text = @"World!";

return customCell;

Everything works fine. However from the tutorials I've seen, it looks like when changing the labels' values I should be doing this instead:

UILabel *firstLabel = (UILabel *)[customCell.contentView viewWithTag:555];
firstLabel.text = @"Hello";

UILabel *secondLabel = (UILabel *)[customCell.contentView viewWithTag:556];
secondLabel.text = @"World!";

(The labels' tag values have been set in the NIB).

Can someone tell me which method is preferred and why?

Thanks!

like image 559
cravr Avatar asked Sep 03 '10 02:09

cravr


1 Answers

viewWithTag: is just a quick and dirty way to pull out child views without having to set up IBOutlet properties on the parent, or even without having to create a UITableViewCell subclass.

For very simple cases this is an acceptable solution, that's what viewWithTag: was intended for. However if you are going to reuse that cell a lot or you want it to have a more developer-friendly interface then you will want to subclass and use real properties as in your first example.

So use viewWithTag: if it's a very simple cell you designed in IB with no subclass and with just a couple of labels. Use a cell subclass with real properties for anything more substantial.

like image 171
Mike Weller Avatar answered Sep 19 '22 05:09

Mike Weller