【问题标题】:Reusable UITableView's prototype cell可重用 UITableView 的原型单元格
【发布时间】:2014-05-18 21:43:45
【问题描述】:

我想创建一个原型单元格,可以通过情节提要在不同的表格视图中使用.. 这样做的正确方法是什么?任何指针表示赞赏。

【问题讨论】:

  • 您能否更深入地了解原型在您的情况下意味着什么?

标签: ios uitableview reusability


【解决方案1】:

我不认为您可以创建原型单元格并在情节提要中的表格之间共享它,但您可以在 nib 中创建原型单元格,然后在 ViewDidLoad 方法中加载它,然后在表格视图中使用它。真的很简单,方法如下……

A.添加笔尖文件:
1. 选择新建文件... 2. 选择 IOS -> 用户界面
3. 选择“Empty” -> 这将在您的项目中添加一个新文件 .xib 文件
4. 将 UITableViewCell 从对象浏览器拖到您的 xib 文件中并根据自己的喜好进行自定义
5. 使用实用工具窗格更改属性 -> 编辑笔尖非常 类似于编辑故事板。
6. 确保为您的单元命名 - 我选择了名称 cellFromNib,但您可能需要其他名称。

B.在每个表的 viewDidLoad 方法中加载 UITableViewCell:

- (void)viewDidLoad
{
   // load the cell in the nib - the nib can only contain this one UITableViewCell
   [self.tableView
         registerNib:[UINib nibWithNibName:[self @"nibFileNameWithoutExtension"]
                                    bundle:[NSBundle mainBundle]]
                    forCellReuseIdentifier:[self @"cellFromNib"]];
}

C.将 nib 的 tableViewCell 出队...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellFromNib" forIndexPath:indexPath];
    // customize your cell here...
}

D.在情节提要的 TableView 中添加一个“虚拟”原型单元格。 从这个“虚拟”单元格到您希望在选择单元格时显示的视图进行转场 - 确保命名转场 - 在此示例中我将其命名为 @"theSegue"。您将在代码中引用此 segue。

E.最后,添加代码以从该单元格中继续...

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // this is basically what the storyboard does under the hood...
    // make sure you have a "dummy" prototype cell with this segue name for each
    // tableview that uses this cell
    [self performSegueWithIdentifier:@"theSegue" sender:self];
}

如果您想专门化您的单元格代码,请创建一个继承 UITableViewCell 的类

我认为这就是你所需要的一切。

我想说不要害怕做这样的事情,因为如果你对 IOS 编程很认真,你会学到新的东西。它确实使代码可重用性更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    相关资源
    最近更新 更多