表格视图单元格中的 UIButton 操作 [英] UIButton action in table view cell

查看:34
本文介绍了表格视图单元格中的 UIButton 操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为在表视图单元格内按下的按钮运行一个操作.以下代码在我的表视图控制器类中.

I am trying to run an action for a button being pressed within a table view cell. The following code is in my table view controller class.

在我的 UITableViewCell 类中名为 requestsCell 的插座中,按钮被描述为是".

The button has been described as "yes" in an outlet in my class of UITableViewCell called requestsCell.

我正在使用 Parse 来保存数据,并希望在按下按钮时更新对象.我的 objectIds 数组工作正常,cell.yes.tag 也将正确的数字打印到日志中,但是,为了正确运行我的查询,我无法将该数字输入到我的连接"函数中.

I am using Parse to save data and would like to update an object when the button is pressed. My objectIds array works fine, the cell.yes.tag also prints the correct number to the logs, however, I cannot get that number into my "connected" function in order to run my query properly.

我需要一种方法来获取单元格的 indexPath.row 以找到正确的 objectId.

I need a way to get the indexPath.row of the cell to find the proper objectId.

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as requestsCell

    // Configure the cell...

    cell.name.text = requested[indexPath.row]

    imageFiles[indexPath.row].getDataInBackgroundWithBlock{
        (imageData: NSData!, error: NSError!) -> Void in

        if error == nil {

            let image = UIImage(data: imageData)

            cell.userImage.image = image
        }else{
            println("not working")
        }    
    }

    cell.yes.tag = indexPath.row
    cell.yes.targetForAction("connected", withSender: self)

    println(cell.yes.tag)

    return cell
}


func connected(sender: UIButton!) {

    var query = PFQuery(className:"Contacts")
    query.getObjectInBackgroundWithId(objectIDs[sender.tag]) {
        (gameScore: PFObject!, error: NSError!) -> Void in
        if error != nil {
            NSLog("%@", error)
        } else {
            gameScore["connected"] = "yes"
            gameScore.save()
        }
    }

}

推荐答案

Swift 4 &斯威夫特 5:

您需要为该按钮添加目标.

You need to add target for that button.

myButton.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)

当然你需要设置那个按钮的标签,因为你正在使用它.

And of course you need to set tag of that button since you are using it.

myButton.tag = indexPath.row

您可以通过继承 UITableViewCell 来实现这一点.在界面构建器中使用它,在该单元格上放置一个按钮,通过插座连接它,然后就可以了.

You can achieve this by subclassing UITableViewCell. Use it in interface builder, drop a button on that cell, connect it via outlet and there you go.

获取连接函数中的标签:

To get the tag in the connected function:

@objc func connected(sender: UIButton){
    let buttonTag = sender.tag
}

这篇关于表格视图单元格中的 UIButton 操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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