[英]Custom UITableViewCell from a .xib file
我正在尝试使用来自.xib文件的自定义UITableViewCell
在拥有UITableView的ViewController中,我已经执行了以下操作:
Ctrl +将tableViewDataSource和tableViewDelegate拖动到Interface Builder中的该View Controller。
这段代码:
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;
}
}
在CustomCell中,我只有一个标签可以简化操作:
import UIKit
class ResultsFoundTableViewCell: UITableViewCell {
@IBOutlet weak var lbStoreName: UILabel!
}
我得到的错误是:
由于未捕获的异常“ NSInternalInconsistencyException”而终止应用程序,原因:“为标识符注册的无效笔尖(ResultsFoundTableViewCell)-笔尖必须仅包含一个顶级对象,该对象必须是UITableViewCell实例”
你知道为什么会这样吗?
该问题的原因是,您必须将所有UI组件放在cell-> contentView内 ,如果其中没有任何元素,则笔尖注册将失败
也可以在不进行描述的情况下进行笔尖声明
let customCellNib = UINib.init(nibName: "nibClassName", bundle: nil);
self.tableView.register(customCellNib, forCellReuseIdentifier: customCellName);
作为String(describing
在此处String(describing
let customCellName = String(describing: ResultsFoundTableViewCell.self);
向字符串内容添加可选内容,例如Optional(“ nibClassName”)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.