如何使用选择器通过函数传递两个参数

时间:2018-11-24 16:23:36

标签: ios swift selector

cellForRowAtIndexPath中,我试图将开关选择和字符串传递给选择器函数,但我无法通过。请帮忙。

let pidName = "someString"
cell.switchSelection.tag = indexPath.row
    cell.switchSelection.addTarget(self, action: 
 #selector(self.switchOperation(_:pid:)), for: .valueChanged)

在这里,我必须通过发件人和pidName,但失败了

@objc func switchOperation(_ sender: UISwitch, pid: Any){
     let store = (sender).isOn
     let settingTag = pid
}

2 个答案:

答案 0 :(得分:1)

正确的解决方案是将操作移至您的单元格类中:

class MyCell: UITableViewCell {
    @IBOutlet weak var switchSelection: UISwitch!

    override func awakeFromNib() {
        super.awakeFromNib()
        switchSelection.addTarget(self, action: #selector(MyCell.action(_:)), for: .valueChanged)
    }

    func configure(switchAction: @escaping (Bool) -> Void) {
        self.switchAction = switchAction
    }

    @objc func action(_ sender: UISwitch) {
        switchAction(sender.isOn)
    }

    private var switchAction: (Bool) -> Void = { _ in }
}

现在在表视图委托中,您可以执行以下操作:

let pidName = "someString"
cell.configure(switchAction: { [weak self] isOn in 
    let store = isOn 
    let settingTag = pid
}

或者您可以这样做:

let pidName = "someString"
cell.configure(switchAction: { [weak self] isOn in 
    self?.switchOperation(isOn: isOn, pid: pid)
}

@objc func switchOperation(isOn: Bool, pid: Any){
    let store = isOn
    let settingTag = pid
}

答案 1 :(得分:0)

您不能使用其他参数

cell.switchSelection.addTarget(self, action: 
#selector(self.switchOperation(_:)), for: .valueChanged)

仅发送与目标添加到对象的类型相同的一个参数

您需要将某处的开关标签设置为pid并像这样使用它

@objc func switchOperation(_ sender: UISwitch) {
   print(sender.tag)
}