使用nib文件而不是故事板中的原型单元格

59

为了更好地重复利用,我想在我的Storyboard之外创建一个表格视图。

现在当我在Xcode中创建一个基于Nib的UITableView视图控制器时,我会在nib文件中得到默认的TableView。然而,在Interface Builder中我无法像在我的Storyboard中那样添加原型单元格。

目前是否不可能在nib中添加原型单元格,或者我漏掉了什么。

非常感谢任何帮助。


1
除了上面的正确答案,我还想提供一个非常详细的解决方案。- StackAnswer链接(使用UITableView:registerNib:forCellReuseIdentifier:tableView:cellForRowAtIndexPath:.xib文件) - skywinder
这个问题/答案对我来说有点困惑。我来这里是为了寻找在xib中定义表视图时如何使用原型单元格的方法。在故事板中完全可以实现,但在xib中却没有这样的功能。 - Jonny
2个回答

92

iOS 5在UITableView上新增了一个方法:registerNib:forCellReuseIdentifier:

使用该方法,需要将UITableViewCell放入一个nib文件中,而且UITableViewCell必须是nib中的唯一根对象。

可以在加载tableView后注册该nib文件,然后当使用cell identifier调用dequeueReusableCellWithIdentifier:时,它将从nib中提取相应的cell,就像使用Storyboard原型单元格一样。


1
太棒了 - 我正想知道如何做到这一点,搜索了这里,看到了你的答案,然后发现我的答案(结果是错误的!)被接受了。Besi,你应该接受这个答案。 - jrturton
2
有没有办法将这些单元格的文件所有者设置为它们所在的控制器? - nicktmro
3
唯一的缺点是你必须自己连接所有操作选择器,我通过在willDisplayCell期间调用addTarget,然后在cell的prepareForReuse方法中调用removeTarget来完成这项任务。有没有更聪明的方法可以让你在Storyboard中连接这些东西? - Duane Fields
感谢您提到这一点:“它必须是nib中唯一的根对象。”我试图将我的tableviewcell和view nib组合在一起,但找不到任何关于UINib如何找到我的tableviewcell的信息。这解决了我的问题! - cbowns
我可以问一下,如果您不想使用自定义的.nib文件怎么办?假设我只想要带有textLabel的基本UITableViewCells。在“cellForRowAtIndexPath”函数中,我应该指定什么reuseIdentifier名称?与故事板中的UITableView不同,在UITableViewController位于自己的.xib文件中时,没有地方定义reuseIdentifier。 - Mike Gledhill
显示剩余4条评论

7

在Swift 4中:

  1. Create new CocoaTouch Class, Subclass from UITableViewCell.
  2. Important - Enable the checkbox 'Also create XIB file' which creates a Swift file and a .xib file
  3. Add labels in the Xib, as you would do for a prototype cell in Storyboard
  4. Connect label outlets to the new swift file
  5. Important - Register the nib file in viewDidLoad

    yourTableview.register(UINib.init(nibName: "CustomCellTableViewCell", bundle: nil), forCellReuseIdentifier: "Cell")
    

    (or)

    yourTableview.register(UINib(nibName: "CustomCellTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "Cell")
    
  6. Implement the datasource and delegates as normal and typecaste to the CustomCell in cellForRowAtIndexPath.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接