18

有没有办法加载原型单元以及故事板中定义的任何 IBOutlet 连接?

更新

我想对单元格进行单元测试(该母校的 UICollectionViewCell),因此想在 UIViewController 上下文之外加载它。

实际上,就像您可以从 nib 加载自定义视图一样,指定其文件的所有者并设置其 IBOutlet(s)。

4

2 回答 2

13

编辑:据我所知,除了您在其中创建的 ViewController 之外,不可能在 Storyboard 的任何地方使用原型 UITableViewCells。

我还没有通过单元测试尝试过这个,但是你可以很容易地把你的自定义UITableViewCell放到一个单独的 nib 中。

要在视图控制器中使用它,您需要将单元格注册到tableViews。

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

然后像这样使用单元格cellForRowAtIndexPath:

static NSString *CellIdentifier = @"myCustomCell";

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

为了您的测试目的,您应该能够使用:

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

如果您需要测试重用行为,您应该在此处设置重用标识符并调用prepareForReuse单元格。

于 2014-03-10T08:44:11.937 回答
11

通常你创建一个UITableViewController或一个UITableView。比你还应该创建一个UITableViewCell类。创建UITableViewCell类后,转到`UIStoryboard,选择单元格:

在此处输入图像描述

然后在UITableViewCell里面设置类Identity Inspector

在此处输入图像描述

现在添加元素UITableViewCell并将它们与您的类连接起来

在此处输入图像描述

现在在CellIdentifier里面添加Attributes Inspector

在此处输入图像描述

没有得到你UITableViewControllerUIViewController你有UITableViewDelegate方法的地方并像这样调用你的单元格(不要忘记你顶部的#import类:UITableViewCellViewController

- (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;
}
于 2014-03-07T18:11:14.393 回答