iOS Swift Button表格视图单元格中的动作

前端之家收集整理的这篇文章主要介绍了iOS Swift Button表格视图单元格中的动作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试为在表格视图单元格中按下的按钮运行一个动作.以下代码在我的表视图控制器类中.该按钮在我的UITableViewCell类别中的一个插座中被描述为“是”,名为requestsCell.我使用解析来保存数据,并希望在按下按钮时更新对象.我的objectIds数组工作正常,cell.yes.tag也会将正确的数字打印到日志中,但是,为了正确运行我的查询,我无法将该数字输入到我的“已连接”函数中.我需要一种获取单元格的indexPath.row的方法来找到适当的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()
        }
    }

}

解决方法

您需要添加该按钮的目标.
myButton.addTarget(self,action: "connected:",forControlEvents: .TouchUpInside)

当然,您需要设置该按钮的标签,因为您正在使用该按钮.

myButton.tag = indexPath.row

您可以通过将UITableViewCell进行子类化来实现此目的.在界面构建器中使用它,在该单元格上放一个按钮,通过插座连接到那里.

编辑:
要在连接的功能获取标签

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

EDIT2:

这个答案是针对swift 1.2提供的,正如评论中所提到的那样,swift 2.2的语法有所不同.

myButton.addTarget(self,action: #selector(ClassName.FunctionName(_:),forControlEvents: .TouchUpInside)

EDIT3:

更新为Swift 3

myButton.addTarget(self,action: #selector(ClassName.FunctionName.buttonTapped),for: .touchUpInside)
原文链接:https://www.f2er.com/iOS/336768.html

猜你在找的iOS相关文章