Ios 注册UITableViewCell不工作
我正在尝试在Ios 注册UITableViewCell不工作,ios,swift,uitableview,swift3,Ios,Swift,Uitableview,Swift3,我正在尝试在viewdiload self.tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell") 在CellForRowatinex中 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell =
viewdiload
self.tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")
在CellForRowatinex中
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell") as! CustomTableViewCell
cell.productNameLabel.text = "Product"
cell.productNameLabel.textColor = UIColor.darkGray
return cell
}
在这里,它正在cell.productNameLabel.text中崩溃
注册手机的目的是什么?为什么会崩溃?
即使单元格或表格不可见,我也要重新加载数据
Crashreport:您是否为此单元格使用xib?如果是这样,如果您只注册单元的类别,则不会连接任何插座。您需要注册实际的xib文件,以便在创建单元时可以正确连接所有内容。看看
-(void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier
请参阅苹果的评论,其中回答了您关于注册手机的问题:
在对任何单元格进行排队之前,请调用此方法或
register(uu:forCellReuseIdentifier:)方法来告诉表视图如何
创建新的单元格。如果指定类型的单元格当前不可用
在重用队列中,表视图使用提供的信息
自动创建新的单元对象
这是我在使用自定义单元格时应用的标准程序(如果您使用的是xib):
在Xib的属性检查器中设置单元格标识符:
注册号Xib:
self.tableTasks.register(UINib(nibName: "TaskCell", bundle: nil), forCellReuseIdentifier: "taskCell")
但是,如果不使用Xib并仅使用代码创建自定义单元格,请使用RegisterCell:
self.tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")
我的方法注册细胞
语法糖
显示崩溃报告阅读以了解注册单元的目的请注意,如果单元在Interface Builder中设计为原型单元,则不得注册单元如果要为CustomTableViewCell创建xib,则应执行registerNib,否则无需注册单元如果您是从UITableView自身执行此操作,则获得了什么崩溃报告@辛图
protocol BSCellProtocol {
// For `registerCell`
static var NibName: String! { get }
// For `registerCell`, `dequeueCellWithType`, and `dequeueHeaderFooterWithType`
static var Identifier: String! { get }
}
extension UITableView {
func registerCell(_ type: BSCellProtocol.Type) {
let nib = UINib(nibName: type.NibName, bundle: nil)
let identifier = type.Identifier!
self.register(nib, forCellReuseIdentifier: identifier)
}
func dequeueCellWithType<T: BSCellProtocol>(_ type: T.Type) -> T {
let cell = self.dequeueReusableCell(withIdentifier: type.Identifier) as! T
return cell
}
func dequeueCellWithType<T: BSCellProtocol>(_ type: T.Type, index: IndexPath) -> T {
let cell = self.dequeueReusableCell(withIdentifier: type.Identifier, for: index) as! T
return cell
}
}
class MyCustomCell: UITableViewCell, BSCellProtocol {
static var NibName: String! = "MyCustomCell"
static var Identifier: String! = "cellIdentifier_at_Xib"
@IBOutlet weak var lblTitle: UILabel!
// other IBOutlet components
}
// In ViewController, register cell
tableView.registerCell(MyCustomCell.self)
// dequeue cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// cell is `MyCustomCell` instance
let cell = tableView.dequeueCellWithType(MyCustomCell.self)
// configure cell ...
// ....
return cell
}