[英]Custom UITableViewCell from a .xib file
I'm trying to use a custom UITableViewCell from a .xib file 我正在尝试使用来自.xib文件的自定义UITableViewCell
In the ViewController where I have the UITableView I already did the following: 在拥有UITableView的ViewController中,我已经执行了以下操作:
Ctrl + Drag the tableViewDataSource and the tableViewDelegate to this View Controller in the Interface Builder. Ctrl +将tableViewDataSource和tableViewDelegate拖动到Interface Builder中的该View Controller。
And this code: 这段代码:
import UIKit
class ResultsFoundViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self;
self.tableView.delegate = self;
//Register my Custom Cell
let customCellName = String(describing: ResultsFoundTableViewCell.self);
let customCellNib = UINib.init(nibName: customCellName, bundle: nil);
self.tableView.register(customCellNib, forCellReuseIdentifier: customCellName);
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5;
}
// MARK: UITableViewDataSource Functions
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ResultsFoundTableViewCell", for: indexPath) as! ResultsFoundTableViewCell;
cell.lbStoreName.text = "Name";
return cell;
}
}
In the CustomCell I only have a label to make it simpler: 在CustomCell中,我只有一个标签可以简化操作:
import UIKit
class ResultsFoundTableViewCell: UITableViewCell {
@IBOutlet weak var lbStoreName: UILabel!
}
The error I get is: 我得到的错误是:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'invalid nib registered for identifier (ResultsFoundTableViewCell) - nib must contain exactly one top level object which must be a UITableViewCell instance'
由于未捕获的异常“ NSInternalInconsistencyException”而终止应用程序,原因:“为标识符注册的无效笔尖(ResultsFoundTableViewCell)-笔尖必须仅包含一个顶级对象,该对象必须是UITableViewCell实例”
Do you know why is this happening? 你知道为什么会这样吗?
The reason of this problem is that you must put all your UI components inside the cell->contentView , if any element is out of it , the nib registration will fail 该问题的原因是,您必须将所有UI组件放在cell-> contentView内 ,如果其中没有任何元素,则笔尖注册将失败
Also make nib declaration without Describting 也可以在不进行描述的情况下进行笔尖声明
let customCellNib = UINib.init(nibName: "nibClassName", bundle: nil);
self.tableView.register(customCellNib, forCellReuseIdentifier: customCellName);
As String(describing
here 作为
String(describing
在此处String(describing
let customCellName = String(describing: ResultsFoundTableViewCell.self);
adds optional to string content like this Optional("nibClassName") 向字符串内容添加可选内容,例如Optional(“ nibClassName”)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.