开发者

Reusable TableViewCell in Interface Builder WITH changeable labels?

How do I make a reusable TableViewCell in Interface Builder with changeable labels?

Is this even possible? From what I understand apple has been giving custom TableViewCell in Interface Builder some love lately, so this should be possible?

Ps. I know there are a lot of开发者_运维问答 questions with answers about TableViewCell in IB, but I couldn't find anyone that made labels work.


You can change anything in a cell that is being re-used. To customize labels that you create in IB, you should set their tags in IB itself & fetch the label using the same tag.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    MyCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell == nil)
    {
        cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }


    // Configure the cell.
    //Do anything here with the labels. Even add or remove them.
    (UILabel*) label1 = (UILabel*)[cell viewWithTag:1];
    return cell;
}


I used to do it he same way as in accepted answer, but I've always felt using tags like I'm using "go to" in Pascal. Feels dirty. But maybe it's just me, tags work just fine.

There's an alternative way though. Subclass a UITableViewCell, create an IBOutlet property, connect in IB, and reference your property in cellForRowAtIndexPath: code. Like so:

interface MyCustomCell : UITableViewCell

@property (nonatomic, weak) IBOutlet UILabel *myAwesomeLabel;

@end

Don't forget to set you cell's class to MyCustomCell in IB.

Reusable TableViewCell in Interface Builder WITH changeable labels?

After that you can connect your property in IB directly like so

Reusable TableViewCell in Interface Builder WITH changeable labels?

And in your Table View Data Source now you can access this property

#import "MyCustomCell.h"


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

    MyCustomCell *cell = (MyCustomCell *)[tableView dequeueReusableCellWithIdentifier:@"MyCell"];

    if (cell) {
        cell.myAwesomeLabel.text = @"Hello, World!";
    }

    return cell;

}

Using tags is error-prone and might turn into a mess very quickly if you use a lot of them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜