Swift 如何将参数传入@objc函数

Swift 如何将参数传入@objc函数,swift,uitableview,delegates,swift4,selector,Swift,Uitableview,Delegates,Swift4,Selector,我在tableView中有一个单元格,其中有一个按钮我想添加一个操作 该按钮将是一个电子邮件地址。按下按钮时,我想触发一个代理,让另一个ViewController打开一封电子邮件。然而,我需要能够将电子邮件作为一个参数传递,而Swift似乎不允许我这样做 相关代码如下: func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let r

我在tableView中有一个单元格,其中有一个按钮我想添加一个操作

该按钮将是一个电子邮件地址。按下按钮时,我想触发一个代理,让另一个ViewController打开一封电子邮件。然而,我需要能够将电子邮件作为一个参数传递,而Swift似乎不允许我这样做

相关代码如下:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let row = self.sections[indexPath.section].rows[indexPath.row]
       switch row {
       case .Email:
            cell.infoLabel.setTitle(cellInfo.email, for: .normal)
            cell.infoLabel.addTarget(self, action: #selector(emailPressed(recipient: cellInfo.email!)), for: .touchUpInside)
            cell.imageType.image = UIImage(named: "Email")
       }
}

@objc func emailPressed(recipient: String){
        self.delegate?.dataController(self, recipientEmail: recipient)
    }

protocol DataControllerDelegate: class {
    funcdataController(_ DataController: DataController, recipientEmail: String)
}
我得到一个错误:“#selector”的参数没有引用“@objc”方法、属性或初始值设定项”


是否有办法将电子邮件传递给@objc函数,以便它可以传入委托函数?

您不能将任何内容传递给目标的操作方法。您不调用该方法;点击按钮时,目标操作体系结构会调用它。action方法必须有一个参数,即sender(在本例中是按钮)


如果操作方法在调用时需要更多信息,则必须以其他方式提供该信息,例如,作为操作方法调用时可以访问的实例属性。

您可以将
UIButton
子类化,并向其添加
recipientEmail
变量

class RecipientButton: UIButton {

    var recipientEmail: String?

    override init(frame: CGRect) {
        super.init(frame: frame)

    }

    required init(coder aDecoder: NSCoder) {
        fatalError("This class does not support NSCoding")
    }
}
在您的单元格中,不要将
infoLabel
作为类型
ui按钮
将其作为类型
RecipientButton

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let row = self.sections[indexPath.section].rows[indexPath.row]
    switch row {
        case .Email:
            cell.infoLabel.setTitle(cellInfo.email, for: .normal)
            cell.infoLabel.recipentEmail = cellInfo.email
            cell.infoLabel.addTarget(self, action: #selector(emailPressed(_ :)), for: .touchUpInside)
            cell.imageType.image = UIImage(named: "Email")
    }
}

@objc func emailPressed(_ sender: RecipientButton) {
    guard let email = sender.recipientEmail else { return }
    self.delegate?.dataController(self, recipientEmail: email)
}