ios 笔尖中的原型单元而不是故事板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8574188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Prototype Cells in a nib instead of a storyboard
提问by Besi
For better re-usability I want to create a table view outside of my Storyboard.
为了更好的可重用性,我想在我的故事板之外创建一个表格视图。
Now when I create a UITableView
based ViewController with Nib in Xcode I get the default TableView in the nib file. However, I am not able in Interface Builder to add prototype cells like I am in my Storyboard.
现在,当我UITableView
在 Xcode 中使用 Nib创建一个基于 ViewController 时,我会在 nib 文件中获得默认的 TableView。但是,我无法在 Interface Builder 中像在 Storyboard 中那样添加原型单元格。
Is it currently not possible to add prototype cells in a nib or am I missing something.
目前是否无法在笔尖中添加原型单元格,或者我遗漏了什么。
Thanks very much for any help.
非常感谢您的帮助。
回答by Richard Venable
iOS 5 includes a new method on UITableView: registerNib:forCellReuseIdentifier:
iOS 5 在 UITableView 上包含了一个新方法:registerNib:forCellReuseIdentifier:
To use it, put a UITableViewCell in a nib. It has to be the only root object in the nib.
要使用它,请将 UITableViewCell 放入笔尖。它必须是笔尖中唯一的根对象。
You can register the nib after loading your tableView, then when you call dequeueReusableCellWithIdentifier: with the cell identifier, it will pull it from the nib, just like if you had used a Storyboard prototype cell.
您可以在加载 tableView 后注册笔尖,然后当您使用单元格标识符调用 dequeueReusableCellWithIdentifier: 时,它将从笔尖中拉出它,就像您使用 Storyboard 原型单元格一样。
回答by Naishta
In Swift 4:
在 Swift 4 中:
- Create new CocoaTouch Class, Subclass from UITableViewCell.
- Important- Enable the checkbox 'Also create XIB file'which creates a Swift file and a .xib file
- Add labels in the Xib, as you would do for a prototype cell in Storyboard
- Connect label outlets to the new swift file
Important- Registerthe 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")
- Implement the datasource and delegates as normal and typecaste to the CustomCell in cellForRowAtIndexPath.
- 从 UITableViewCell 创建新的 CocoaTouch 类,子类。
- 重要- 启用复选框“同时创建 XIB 文件”,这将创建一个 Swift 文件和一个 .xib 文件
- 在 Xib 中添加标签,就像在 Storyboard 中添加原型单元格一样
- 将标签出口连接到新的 swift 文件
重要-在 viewDidLoad 中注册nib 文件
yourTableview.register(UINib.init(nibName: "CustomCellTableViewCell", bundle: nil), forCellReuseIdentifier: "Cell")
(或者)
yourTableview.register(UINib(nibName: "CustomCellTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "Cell")
- 在 cellForRowAtIndexPath 中实现数据源并像普通和 typecaste 一样委托给 CustomCell。