如何将一个button添加到iOS中的表格视图单元格?

我正在Swift中创build一个生产力应用程序。 我没有使用Storyboard中的原型单元格,因为它大部分已经被编写在代码中了。 我想要一个checkboxbutton。 我将如何去做呢?

虽然Tim的回答在技术上是正确的,但我不会build议这样做。 因为UITableView使用一个出列机制,所以实际上可以接收一个已经有一个button的重用单元(因为你之前添加了它)。 所以你的代码实际上是添加了第二个button(和第三,第四等)。

你想要做的就是从UITableViewCell创build一个子类,它在实例化的时候向它自己添加一个button。 然后你可以从你的UITableView中取出这个单元格,它会自动的在你的button上,而不需要在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!; 

那么,首先你的cellForRowAtIndexPath可能应该使用出队机制,所以你在每次虚拟化的时候都不要重新创build单元。

但是,除此之外,您只需要创buildbutton,并将其作为子视图添加到单元格。

 cell.addSubview(newButton) 

但是,当然,您将不得不酌情pipe理大小和布局。

一个UITableViewCell也有一个选定的状态,一个didSelect和didDeselect方法可用于侦听整个单元的抽头。 也许这是一个更实际一点,因为你似乎要检查/取消选中checkbox,这几乎是select相同。 您可以在离开后将单元格设置为选定状态。