ios - Swift 4:无法在包中加载 NIB:自定义 UITableViewCell 的“NSBundle”(无 IB)
问题描述
我已经构建了自己的 UITableViewCell (完全通过代码,没有界面构建器)并且我得到了休闲异常:
[...] NSInternalInconsistencyException',原因:'无法在包中加载 NIB:'NSBundle [...]
我相当确定我不需要使用 awakeFromNib() (请参阅代码),但这是我将它作为“不可重用”传递时让它工作的唯一方法
// this works
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath [...] {
return myCustomCell()
// this fails
tableView.register(MyCustomCell.self, forCellReuseIdentifier: "foo")
//throws immediately after this line: "[...] Could not load NIB in bundle"
我的自定义单元格:
class TextValueTableViewCell: UITableViewCell {
let textField: UITextField = UITextField(
frame: CGRect(x: 30, y: 5, width: 350, height: 25)
)
let label = UILabel(frame: CGRect(x: 30, y: 5, width: 350, height: 25))
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.awakeFromNib();
}
override func awakeFromNib() {
super.awakeFromNib()
self.label.text = "oh"
self.contentView.addSubview(self.label)
self.contentView.addSubview(self.textField)
self.textField.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: -25).isActive = true
self.textField.translatesAutoresizingMaskIntoConstraints = false;
self.textField.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor, constant: 0).isActive = true
self.textField.widthAnchor.constraint(equalTo: self.label.widthAnchor, constant: 0).isActive = true
self.textField.textAlignment = .right;
self.textField.placeholder = "Account Name"
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
}
正如我所说,我没有使用界面构建器(而且我没有计划使用它)所以我不确定它为什么会尝试从包中加载一些东西。具体来说,我不必将其注册为NIB吗?
tableView.register(<#T##nib: UINib?##UINib?#>, forCellReuseIdentifier: <#T##String#>)
解决方案
例如,如果您使用 UIViewController 类名作为 TextPicker 那么您需要像 Bellow Code 一样使用
let bundle = Bundle(for: TextPicker.self)
super.init(nibName: "TextPicker" , bundle: bundle)
如果您在其他项目中使用 TableView 和 Xib 作为框架
tableView.register(UINib.init(nibName: "TextPickerCell", bundle: bundle), forCellReuseIdentifier: "TextPickerCell")
let bundle = Bundle(for: TextPicker.self)
推荐阅读
- c++ - 从 Win32 API 的 C++11 线程获取本机线程句柄
- powerbi - 切片器 - 更改显示值
- laravel - Laravel cashier-paddle Simple Charge 结账 id 问题
- flutter - 使用 Bloc 从 ListView 中删除特定项目
- html - 嵌套在有序列表中的无序列表
- java - 迭代可以是另一个对象的对象字段
- graphileon - 如何使我应用于节点的样式显示给访问 Graphileon 中相同数据存储的其他用户?
- python - 枢轴熊猫数据框具有多索引列
- menu - Shopify 汉堡菜单按钮在移动设备上不起作用(首次亮相主题)
- python - python中的内部类不影响程序正常运行