Use XIB from parent class in UITableViewCell

I currently have a feed with custom UITableViewCells, for example:

NewsCell.m NewsCell.xib NewsCell_Friends.m NewsCell_Friends.xib NewsCell_CheckinPhoto.m NewsCell_CheckinPhoto.xib 

[...]

NewsCell_Friends and NewsCell_Checkin inherit both from NewsCell (methods and elements such as titleLabel, dateLabel, which are shared by all subclasses)

At the moment, I have never used the NewsCell class itself, and only subclasses, since each type of news has a very clear layout (Xib).

Let's say now that I would like to have an easy implementation from the point of view of the user interface of my news feed, where all cells have the same appearance, the same height and the same content: titleLabel and dateLabel. (Actually, for example, a stream of notifications).

What I would like to do is reuse NewsCell.xib as separate for each type of news, for example. below:

 NewsCell_CheckinPhoto *cell = [tableView dequeueReusableCellWithIdentifier:@"CheckinPhoto"]; if (!cell){ UIViewController *c = [[UIViewController alloc] initWithNibName:@"NewsCell" bundle:nil]; cell = (NewsCell_CheckinPhoto *)c.view; cell.parent = self; } [cell configureCell:indexPath withNews:news]; return cell; 

in the delegate methods cellForRowAtIndexPath .

Please note that I am using xib, not NewsCell_CheckinPhoto xib in this controller.

But it doesn’t work: the nib file is well loaded, and the contents of NewsCell.xib displays well in the cell, BUT setting labels (for example, titleLabel.text = @ "Robert took a photo") in the NewsCell_CheckinPhoto class does not work and is not even called.

It only works if I specify the class type * NewsCell_CheckinPhoto * in the NewsCell.xib file, but this will not allow me to reuse NewsCell.xib to render each NewsCell subclass with a sample and unique presentation.

+4
source share
1 answer

When I understand you correctly, you want to load a cell from XIB.
You should not do this with

UIViewController *c = [[UIViewController alloc] initWithNibName:@"NewsCell" bundle:nil]; but put only the cell in the XIB and then load it with

UITableViewCell *cell = [[NSBundle mainBundle] loadNibNamed:@"NewsCell"][0];

or similar (please check documents).

Also remember, when you load something like a table view cell from XIB, it is initialized with initWithCoder: rather than init or initWithFrame: This may be the reason why your points are not intinalized.

0
source

Source: https://habr.com/ru/post/1498617/


All Articles