如何在 iOS 中向表格视图单元格添加按钮? [英] How to add a button to a table view cell in iOS?

查看:22
本文介绍了如何在 iOS 中向表格视图单元格添加按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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).

您想要做的是从 UITableViewCell 创建一个子类,它在实例化时向自身添加一个按钮.然后,您可以从 UITableView 中将该单元格出列,它会自动在其上放置您的按钮,而无需在 cellForRowAtIndexPath 方法中执行此操作.

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.

像这样:

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 中实际出列它.

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!;

这篇关于如何在 iOS 中向表格视图单元格添加按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆