定制配件视图button的动作是什么 – swift

这似乎已经被迅速和objc问了几次,但我不能迅速看到一个正确的答案,所以希望这次有人能帮助我。 我创build了一个自定义配件视图button,但需要正确的button操作:“accessoryButtonTapped”是一个无法识别的select器。

什么是select器需要调用tableViewCellDelegate方法willSelectRowAtIndexPath?

我有的代码是:

let cellAudioButton = UIButton(type: .Custom) cellAudioButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20) cellAudioButton.addTarget(self, action: "accessoryButtonTapped", forControlEvents: .TouchUpInside) //INCORRECT ACTION: cellAudioButton.setImage(UIImage(named: "blueSpeaker.png"), forState: .Normal) cellAudioButton.contentMode = .ScaleAspectFit cell.accessoryView = cellAudioButton as UIView 

在此先感谢任何可以帮助的人。

为什么你需要调用willSelectRowAtIndexPath ? 你已经做好了一切,并解决你unrecognized selector错误只是做一个函数,当你点击cell.accessoryView将被调用。 在你的情况下:

 func accessoryButtonTapped(){ print("Tapped") } 

更新
如果你想获得indexPath你可以

添加一个标签到你的cellAudioButton

 cellAudioButton.tag = indexPath.row 

在你的addTarget添加一个:传递一个参数

并在你的function

 func accessoryButtonTapped(sender : AnyObject){ print(sender.tag) print("Tapped") } 

所以整个代码:

 let cellAudioButton = UIButton(type: .Custom) cellAudioButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20) cellAudioButton.addTarget(self, action: "accessoryButtonTapped:", forControlEvents: .TouchUpInside) cellAudioButton.setImage(UIImage(named: "blueSpeaker.png"), forState: .Normal) cellAudioButton.contentMode = .ScaleAspectFit cellAudioButton.tag = indexPath.row cell.accessoryView = cellAudioButton as UIView func accessoryButtonTapped(sender : AnyObject){ print(sender.tag) print("Tapped") } 

Swift 3.1更新了Rashwan的解决scheme

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) //add button as accessory view let cellAudioButton = UIButton(type: .custom) cellAudioButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30) cellAudioButton.addTarget(self, action: #selector(ViewController.accessoryButtonTapped(sender:)), for: .touchUpInside) cellAudioButton.setImage(UIImage(named: "closeRed"), for: .normal) cellAudioButton.contentMode = .scaleAspectFit cellAudioButton.tag = indexPath.row cell.accessoryView = cellAudioButton as UIView return cell } func accessoryButtonTapped(sender : UIButton){ print(sender.tag) print("Tapped") } 

注意:

这里的ViewController是像LoginViewController这样的Class的名字