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

戏子无情 提交于 2019-12-08 13:57:57

问题


I'm creating a productivity app in Swift. I'm not using a prototype cell in the Storyboard as most of it has been written in code already. I'd like to a checkbox button. How would I go about doing that?


回答1:


While the answer from Tim is technically correct, I would not advise on doing this. Because the UITableView uses a dequeuing mechanism, you could actually receive a reused cell which already has a button on it (because you added it earlier). So your code is actually adding a 2nd button to it (and a 3rd, 4th, etc).

What you want to do, is create a subclass from the UITableViewCell which adds a button to itself, while it is being instantiated. Then you can just dequeue that cell from your UITableView and it will automatically have your button on it, without the need to do it in the cellForRowAtIndexPath method.

Something like this:

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
    }

}

And then you can actually dequeue it in the cellForRowAtIndexPath like this.

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



回答2:


Well, first of all your cellForRowAtIndexPath should probably use the dequeue mechanism so you aren't recreating cells every time when virtualizing.

But that aside, all you need to do is create the button, and add it as a sub view to the cell.

cell.addSubview(newButton)

But of course then you will have to manage the sizing and layout as appropriate.




回答3:


A UITableViewCell also has a selected state and a didSelect and didDeselect method available that listens to taps on the whole cell. Perhaps that's a bit more practical since you seem to want to check/uncheck checkboxes, which is more or less the same as selecting. You could set the cell in selected state right after you dequeued it.



来源:https://stackoverflow.com/questions/28787676/how-to-add-a-button-to-a-table-view-cell-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!