表视图单元格中的UIButton操作

Sam*_*mmm 42 parsing uitableview ios swift

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

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

我正在使用Parse来保存数据,并希望在按下按钮时更新对象.我的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()
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

IxP*_*aka 95

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

myButton.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)
Run Code Online (Sandbox Code Playgroud)

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

myButton.tag = indexPath.row
Run Code Online (Sandbox Code Playgroud)

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

编辑: 要在连接函数中获取标记:

@objc func connected(sender: UIButton){
    let buttonTag = sender.tag
}
Run Code Online (Sandbox Code Playgroud)

EDIT2:

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

myButton.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)
Run Code Online (Sandbox Code Playgroud)

EDIT3:

针对Swift 3进行了更新

myButton.tag = indexPath.row
Run Code Online (Sandbox Code Playgroud)

EDIT4:

针对Swift 4进行了更新

@objc func connected(sender: UIButton){
    let buttonTag = sender.tag
}
Run Code Online (Sandbox Code Playgroud)

  • @Andrej而不是使用'action:'connect:"'你必须使用'action:#selector(ClassName.FunctionName(_ :)' (2认同)
  • 如果我有部分并且我需要知道该部分以及该行怎么办 (2认同)

小智 40

使用button.tag按钮实际被按下的信息载体所接受的答案是可靠的并且被广泛接受但是因为标签只能容纳Ints 而受到限制.

您可以利用Swift的强大闭包功能来获得更大的灵活性和更清晰的代码.

我推荐这篇文章:如何使用 Jure Zove的Swift闭包在表视图单元格中正确执行按钮.

适用于您的问题:

  1. 声明可以在你的tableview中保持封闭的可变细胞

    var buttonTappedAction : ((UITableViewCell) -> Void)?
    
    Run Code Online (Sandbox Code Playgroud)
  2. 按下按钮时只添加一个动作,只执行闭包.你以编程方式做到了,cell.yes.targetForAction("connected", withSender: self)但我更喜欢一个@IBAction插座:-)

    @IBAction func buttonTap(sender: AnyObject) {
       tapAction?(self)
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 现在将内容func connected(sender: UIButton!) { ... }作为闭包传递给cell.tapAction = {<closure content here...>}.请参阅文章以获得更准确的解释,请不要忘记在从环境中捕获变量时中断参考周期.

  • 我认为这种方法比`tag`方法要多得多.我一直认为那种方式很挑剔. (3认同)

kal*_*esh 33

检测按钮事件并执行某些操作的简单方法

class youCell: UITableViewCell
{
    var yourobj : (() -> Void)? = nil

    //You can pass any kind data also.
   //var user: ((String?) -> Void)? = nil

     override func awakeFromNib()
        {
        super.awakeFromNib()
        }

 @IBAction func btnAction(sender: UIButton)
    {
        if let btnAction = self.yourobj
        {
            btnAction()
          //  user!("pass string")
        }
    }
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = youtableview.dequeueReusableCellWithIdentifier(identifier) as? youCell
        cell?.selectionStyle = UITableViewCellSelectionStyle.None

cell!. yourobj =
            {
                //Do whatever you want to do when the button is tapped here
                self.view.addSubview(self.someotherView)
        }

cell.user = { string in
            print(string)
        }

return cell

}
Run Code Online (Sandbox Code Playgroud)


lev*_*ese 6

我们可以为按钮创建一个闭包并在 cellForRowAtIndexPath 中使用它

class ClosureSleeve {
  let closure: () -> ()

  init(attachTo: AnyObject, closure: @escaping () -> ()) {
    self.closure = closure
    objc_setAssociatedObject(attachTo, "[\(arc4random())]", self,.OBJC_ASSOCIATION_RETAIN)
}

@objc func invoke() {
   closure()
 }
}

extension UIControl {
func addAction(for controlEvents: UIControlEvents = .primaryActionTriggered, action: @escaping () -> ()) {
  let sleeve = ClosureSleeve(attachTo: self, closure: action)
 addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
 }
}
Run Code Online (Sandbox Code Playgroud)

然后在 cellForRowAtIndexPath 中

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = youtableview.dequeueReusableCellWithIdentifier(identifier) as? youCell
    cell?.selectionStyle = UITableViewCell.SelectionStyle.none//swift 4 style

      button.addAction {
       //Do whatever you want to do when the button is tapped here
        print("button pressed")
      }

    return cell
 }
Run Code Online (Sandbox Code Playgroud)


小智 5

class TableViewCell: UITableViewCell {
   @IBOutlet weak var oneButton: UIButton!
   @IBOutlet weak var twoButton: UIButton!
}


class TableViewController: UITableViewController {

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell

    cell.oneButton.addTarget(self, action: #selector(TableViewController.oneTapped(_:)), for: .touchUpInside)
    cell.twoButton.addTarget(self, action: #selector(TableViewController.twoTapped(_:)), for: .touchUpInside)

    return cell
}

func oneTapped(_ sender: Any?) {

    print("Tapped")
}

func twoTapped(_ sender: Any?) {

    print("Tapped")
   }
}
Run Code Online (Sandbox Code Playgroud)