How do you load a prototype cell from a storyboard?

点点圈 提交于 2019-11-27 23:34:14

Edit: As far as I know, it's not possible to use prototype UITableViewCells from a Storyboard anywhere other than the ViewController you created it in.

I haven't tried this with unit tests yet but you can easily put your custom UITableViewCell into a separate nib.

For using it in your view controllers you need to register the cell with your tableViews.

UINib *nib = [UINib nibWithNibName:@"ABCNameOfYourNibCell" bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier:@"myCustomCell"];

Then use the cell like this in cellForRowAtIndexPath:

static NSString *CellIdentifier = @"myCustomCell";

ABCNameOfYourNibCell *cell = 
[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

For your testing purposes you should be able to go with:

ABCNameOfYourNibCell *testCell = 
[[ABCNameOfYourNibCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:nil];

If you need to test reuse-behaviour, you should set a reuseIdentifier here and call prepareForReuse on the cell.

Normally you crete an UITableViewController or a UITableView. Than you should also create a UITableViewCell class. After creating the UITableViewCell class, go to the `UIStoryboard, select the cell :

Then set the UITableViewCell class inside the Identity Inspector:

Now add elements to the UITableViewCell and connect them with your class

Now add the CellIdentifier inside the Attributes Inspector:

No got to your UITableViewController or the UIViewController where you have the UITableViewDelegate methods and call your cell like this (don't forget to #import the UITableViewCell class at the top of your ViewController:

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

    static NSString *CellIdentifier = @"MyIdentifier";
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier 
                                                   forIndexPath:indexPath];

    [cell.label setText:[NSString stringWithFormat:@"My Cell at Row %ld", 
                         (long)indexPath.row]];      
    return cell;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!