How to pass in parameters into @objc function

孤者浪人 提交于 2019-11-28 14:47:16

You can subclass UIButton and add a recipientEmail variable to it.

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")
    }
}

Inside your cell, instead of having infoLabel as of type UIButton have it as of type 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)
}

You cannot pass anything into a target's action method. You don't call the method; the target-action architecture calls it when the button is tapped. The action method must take one parameter, namely the sender (which in this case will be the button).

If the action method needs more information at the time that it is called, you must provide that information in some other way, e.g. as an instance property that the action method can access when it is called.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!