【发布时间】:2016-09-23 12:02:48
【问题描述】:
我正在尝试以编程方式在表格视图单元格中实现堆栈视图,并向其添加标签和按钮,如下所示:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let dict = self.char[indexPath.row]
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.spacing = 20
stackView.distribution = .fillProportionally
stackView.alignment = .leading
cell.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: cell.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: cell.trailingAnchor)
])
let bornLabel = UILabel()
bornLabel.textColor = UIColor.blue
let bornLabelValue = UILabel()
bornLabelValue.textColor = UIColor.blue
stackView.addArrangedSubview(bornLabel)
stackView.addArrangedSubview(bornLabelValue)
for (key, value) in dict {
bornLabel.text = key
bornLabelValue.text = value
if key == "Height" {
let button = UIButton(type: .roundedRect)
button.setTitle("English", for: .normal)
button.setTitleColor(.blue, for: .normal)
stackView.addArrangedSubview(button)
}
}
return cell
}
问题在于,每次调用tableView.reloadData() 时,都会在现有单元格的顶部添加另一个单元格,根据提供给tableView 的数据,每个标签具有不同的值。或者它可能不会每次都生成另一个单元格,而只是添加另一个堆栈视图。我不知道。我该如何解决这个问题?
谢谢
【问题讨论】:
标签: ios swift uitableview uistackview