自定义配件视图按钮的动作是什么 - swift

ric*_*chc 4 uitableview ios swift

这似乎已经在swift和objc中被问了几次,但是我看不到swift的正确答案,所以希望这次有人可以帮助我.我创建了一个自定义配件视图按钮,但需要正确的按钮操作:因为"accessoryButtonTapped"是一个无法识别的选择器.

调用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
Run Code Online (Sandbox Code Playgroud)

提前感谢任何可以提供帮助的人.

Ras*_*n L 8

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

func accessoryButtonTapped(){
    print("Tapped")
}
Run Code Online (Sandbox Code Playgroud)

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

添加标签到您的cellAudioButton:

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

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

并在你的功能

func accessoryButtonTapped(sender : AnyObject){
        print(sender.tag)
        print("Tapped")
    }
Run Code Online (Sandbox Code Playgroud)

所以整个代码:

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")
    }
Run Code Online (Sandbox Code Playgroud)


Sou*_*rma 6

Swift 3.1更新Rashwan解决方案

 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")
    }
Run Code Online (Sandbox Code Playgroud)

笔记:

这里ViewController的名称,如LoginViewController