Prototype Cells in a nib instead of a storyboard

China☆狼群 提交于 2019-11-26 10:16:50

问题


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.

Is it currently not possible to add prototype cells in a nib or am I missing something.

Thanks very much for any help.


回答1:


iOS 5 includes a new method on UITableView: registerNib:forCellReuseIdentifier:

To use it, put a UITableViewCell in a nib. It has to be the only root object in the nib.

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.




回答2:


In 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.


来源:https://stackoverflow.com/questions/8574188/prototype-cells-in-a-nib-instead-of-a-storyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!