如何将参数传递给@objc函数 [英] How to pass in parameters into @objc function

查看:160
本文介绍了如何将参数传递给@objc函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a cell in a tableView, with a button I want to add an action to.

该按钮将是一个电子邮件地址。当按下按钮时,我想触发一个将使另一个ViewController打开电子邮件的委托。但是,我需要能够将电子邮件作为参数传递,Swift似乎不允许我这样做。

The button will be an email address. When the button is pressed, I want to trigger a delegate that will have another ViewController open up an email. However, I need to be able to pass in the email as a parameter and Swift doesn't seem to let me do that.

相关代码如下:

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'方法,属性或初始化程序

I'm getting the error: "Argument of '#selector' does not refer to an '@objc' method, property, or initializer"

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

Is there a way to pass in the email to the @objc function so that it can feed into the delegate function?

推荐答案

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

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

在您的单元格内部,而不是从 UIButton 开始具有 infoLabel 类型 RecipientButton

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

这篇关于如何将参数传递给@objc函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆