【发布时间】:2020-01-29 04:59:13
【问题描述】:
我需要在表格视图单元格中将标签作为子视图添加到 UIStackView。
我已将标签创建为
let nameLabel=UILabel()
nameLabel.text=names[indexPath.row]
其中 name 是一个数组,类型为 String
我的代码是
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource
{
let names=["Amutha","Priya","Amuthapriya","Priyasri","Kavisha"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return names.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell
{
let cell=tableView.dequeueReusableCell(withIdentifier: "cell") as! ViewCell
for name in names
{
let nameLabel=UILabel()
nameLabel.text=name
cell.nameStackView!.addSubview(nameLabel)
}
return cell
}
}
为什么当我向 stackview 添加标签时出现空指针异常?
任何帮助将不胜感激。
【问题讨论】:
-
显示
ViewCell代码 -
使用
UIStackView时,始终使用addArrangedSubview()并添加到其排列的子视图数组中,而不是常规的addSubview(),因为它根据配置自行管理其子视图。 -
@LokSN 你是对的。但这不是崩溃的原因
-
不是这个意思,只是有一点要说明。从答案上的cmets来看,可能是由于单元格的
nameStackView为nil
标签: ios swift xcode null stackview