我需要用一些按钮制作一个单元格。此按钮是问题的答案选项。但问题和按钮(答案)的数量没有确定,因为我从Alamofire获得这些数据。因此可能有2,3,6或任意数量的按钮。有没有办法以编程方式添加这些按钮,具体取决于(例如)数组中的项目数量,它们看起来很受限制?像堆栈视图?
提前致谢
堆栈视图当然是将任意数量的视图约束到列(或行)中的一种方式。所以这听起来是最好的方式。
这是一种偷偷摸摸的方法,但是如果你知道你将拥有的最大按钮数,你可以直接将它添加到故事板上的自定义原型单元格中,而无需以编程方式添加按钮。
解决方案(用Swift 4编写,但一般答案)
CustomCellTableViewCell.swift
。该文件现在看起来应该是这样的:CustomCellTableViewCell.swift
class CustomCellTableViewCell: UITableViewCell {
@IBOutlet weak var question: UILabel!
@IBOutlet weak var answerOne: UIButton!
@IBOutlet weak var answerTwo: UIButton!
...
...
@IBOutlet weak var answerEight: UIButton!
}
中。请记住将TableviewCell转换为CustomCell:func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCellTableViewCell
var answerButtons = [cell.answerButtonOne, cell.answerButtonTwo..., cell.answerButtonEight]