【发布时间】:2021-01-22 06:37:45
【问题描述】:
我有这个UITableViewCell:
class TableViewCell3: UITableViewCell {
var sectionLabel: String?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setupLabel()
}
func setupLabel() {
let myTextField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 300.00, height: 30.00));
// App crashes here because sectionLabel is nil
myTextField.text = sectionLabel!
self.contentView.addSubview(myTextField)
}
}
如您所见,我试图在每个 UITableViewCell 中显示一个 UITextField。
我试图显示的属性sectionLabel 设置在UITableView 内:
extension MoviesViewController5: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell =
tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as? sectionTableCell2
else {
fatalError("Unable to create explore table view cell")}
cell.sectionLabel = sectionsLabels![indexPath.row]
return cell
}
}
问题是UITableViewCell 在设置sectionLabel 属性之前被初始化。
所以当我尝试显示它时:
myTextField.text = sectionLabel!
应用程序崩溃,因为它是 nil。
是的,我知道我应该添加 nil 检查,但这不是重点。
POINT 是如何显示UItextField AFTER 设置sectionLabel 属性。
【问题讨论】:
-
为什么不在
sectionLabel上使用didSet,然后它会添加值。此外,您不需要解开该值,因为您可以将 nil 放入.text值中。
标签: ios swift uitableview uitextfield tvos