【问题标题】:How to add custom UIButton in table view cell?如何在表格视图单元格中添加自定义 UIButton?
【发布时间】:2015-06-13 01:40:57
【问题描述】:

我有一个自定义的UIButton,我需要将它添加到我的动态表格视图单元格中。我用过的教程都不适合我。我的UIButton 仅在单击单元格时出现,然后迅速消失。当我单击按钮时,应用程序崩溃,我得到...ViewController addButtonPressed]: unrecognized selector sent to instance。我需要在这里做什么?

class TableViewCell: UITableViewCell {

        @IBOutlet weak var addFriendButton: UIButton!

}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBAction func addButtonPressed(sender: UIButton!) {
            println("Hey")
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

            var friendsCell = tableView.dequeueReusableCellWithIdentifier("AddFriendsCell", forIndexPath: indexPath) as! TableViewCell

            friendsCell.addFriendButton.tag = indexPath.row

            friendsCell.addFriendButton.addTarget(self, action: "addButtonPressed", forControlEvents: .TouchUpInside)

            return friendsCell

        }
}

【问题讨论】:

    标签: ios swift uitableview uibutton


    【解决方案1】:

    试试这个:(在您的选择器名称中添加“:”)

    friendsCell.addFriendButton.addTarget(self, action: "addButtonPressed:", forControlEvents: .TouchUpInside)
    

    我希望这能解决您无法识别选择器的问题。

    【讨论】:

    • 是的,成功了!但是我的按钮(我正在使用自定义图像)仍然只在单击单元格时出现。为什么会这样?
    • 我认为您在界面生成器中设置选定状态时设置了单元格样式
    • 对不起,这是什么意思?我应该检查什么?
    • 不,我是通过情节提要添加的
    • 尝试评论这一行:friendsCell.addFriendButton.tag = indexPath.row 然后测试.....
    【解决方案2】:

    我有点糊涂了,下面的函数应该不是outlet:

    @IBAction func addButtonPressed(sender: UIButton!) {
                println("Hey")
    }
    

    TableViewCell 中应该有一个按钮,而 ViewController 中应该只有一个方法,它们应该是同一个按钮吗?

    如果是这样,从 ViewController 及其出口中移除底部,只留下要调用的函数。

    【讨论】:

    • 解决了您的问题吗?
    • 幸运的是,下面的答案有所帮助。这个错误实际上并不重要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多