如何将按钮添加到 iOS 中的 table 视图单元格?

How to add a button to a table view cell in iOS?

我正在 Swift 中创建一个生产力应用程序。我没有在 Storyboard 中使用原型单元,因为其中大部分已经用代码编写。我想要一个复选框按钮。 我该怎么做呢?

好吧,首先,您的 cellForRowAtIndexPath 可能应该使用出队机制,这样您就不会在虚拟化时每次都重新创建单元格。

除此之外,您需要做的就是创建按钮,并将其作为子视图添加到单元格中。

cell.addSubview(newButton)

当然,您必须适当地管理大小和布局。

虽然蒂姆的回答在技术上是正确的,但我不建议这样做。因为 UITableView 使用出队机制,你实际上可以收到一个重用的单元格,上面已经有一个按钮(因为你之前添加了它)。因此,您的代码实际上是向其中添加了第二个按钮(以及第三个、第四个等)。

您想要做的是从 UITableViewCell 创建一个子类,它在实例化时向自身添加一个按钮。然后你可以从你的 UITableView 中取出那个单元格,它会自动把你的按钮放在上面,而不需要在 cellForRowAtIndexPath 方法中做。

像这样:

class MyCustomCellWithButton: UITableViewCell {

    var clickButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton;

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier);

        self.contentView.addSubview(self.clickButton);

    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

然后您实际上可以像这样在 cellForRowAtIndexPath 中将其出列。

var cell = tableView.dequeueReusableCellWithIdentifier("my-cell-identifier") as? MyCustomCellWithButton;
if (cell == nil) {
    cell = MyCustomCellWithButton(style: UITableViewCellStyle.Default, reuseIdentifier: "my-cell-identifier");
}       
return cell!;

UITableViewCell 也有一个选定状态和一个可用的 didSelect and didDeselect 方法来侦听整个单元格上的点击。也许这更实用一些,因为您似乎想要 check/uncheck 复选框,这或多或少与选择相同。您可以在单元格出队后立即将其设置为选中状态。