gpt4 book ai didi

ios - UITableViewCell 不显示

转载 作者:可可西里 更新时间:2023-11-01 00:21:35 27 4
gpt4 key购买 nike

我正在创建一个简单的表格但没有 Storyboard,只是编码,目前我可以创建表格但是当我添加单元格时它崩溃了,这些是我的变量:

var optionsTableView:UITableView!
var options = ["Option1", "Option2"]

当我点击一个按钮时,表格出现,功能是:

@IBAction func Options(sender: AnyObject) {
if optionsTableView != nil {
optionsTableView.removeFromSuperview()
self.optionsTableView = nil
return
}

self.optionsTableView = UITableView()
self.optionsTableView.backgroundColor = UIColor(white: 0, alpha: 0.95)
self.optionsTableView.delegate = self
self.optionsTableView.dataSource = self
self.optionsTableView.translatesAutoresizingMaskIntoConstraints = false

var constraints = [NSLayoutConstraint]()
constraints.append(NSLayoutConstraint(item: optionsTableView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1.0, constant: 100.0))
constraints.append(NSLayoutConstraint(item: optionsTableView, attribute: .Trailing, relatedBy: .Equal, toItem: sender, attribute: .Trailing, multiplier: 1.0, constant: 0))
constraints.append(NSLayoutConstraint(item: optionsTableView, attribute: .Top, relatedBy: .Equal, toItem: sender, attribute: .Bottom, multiplier: 1.0, constant: 5.0))

self.view.addSubview(optionsTableView)
self.view.addConstraints(constraints)

optionsTableView.addConstraints([NSLayoutConstraint(item: optionsTableView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 220.0)])
}

表格的功能:

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.options.count
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44.0
}

到目前为止,一切顺利,但使用 cellForRowAtIndexPath 时,应用程序崩溃了:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = optionsTableView.dequeueReusableCellWithIdentifier("cell")!
if tableView == optionsTableView {
cell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
cell.backgroundView = nil
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.textColor = UIColor.whiteColor()
cell.textLabel?.text = self.options[indexPath.row]
return cell
}
return cell
}

特别是在这一行应用程序崩溃:

var cell = optionsTableView.dequeueReusableCellWithIdentifier("cell")!

控制台显示:“ fatal error :在展开可选值时意外发现 nil”,您认为发生了什么??

最佳答案

该行崩溃是因为它没有找到具有该重用标识符的单元格。

你必须注册它:

self.tableView.registerClass(Cell.self as AnyClass, forCellReuseIdentifier: "cell")

这样当你强制解包时它就不会崩溃。

关于ios - UITableViewCell 不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39296464/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com