向标准文本库 UIBarButtonItem 添加一个动作

Add an action to a standard text base UIBarButtonItem

我相信我已经按照其他 SO 线程的步骤通过另一种方法调用了一个操作,当 UIBarButtonItem 被点击时但是我不断收到以下错误 Argument of '#selector' does not refer to an '@objc' method, property, or initializer 并且错误突出显示 #selector文字。

这是设置按钮:

navigationItem.rightBarButtonItem = UIBarButtonItem(title: "\(barButtonItemText)", style: .done, target: self, action: #selector(inviteMethod(inviteMethod: inviteMethodSelected!)))

这是我在点击按钮时尝试 运行 的方法:

    func inviteMethod (inviteMethod:String) {

    let inviteMethod = inviteMethod

    if inviteMethod == "email" {
        inviteViaEmail(invitedContacts: self.invitedContacts)
    }
    else {
        inviteViaText(invitedContacts: self.invitedContacts)  
    }  }

其中一种邀请方法的示例,以防有帮助

    func inviteViaEmail (invitedContacts:[Contact]) {

    var invitedContactsEmails:[String] = []

    for contactEmails in invitedContacts {

        let emailAddress = contactEmails.emailAddress ?? ""

        invitedContactsEmails.append(emailAddress)

    }

        let mc = MFMailComposeViewController()
        mc.mailComposeDelegate = self as? MFMailComposeViewControllerDelegate

        mc.setToRecipients(invitedContactsEmails)
    mc.setSubject("Invite for Gallery App, Event \(event?.eventName)")

    mc.setMessageBody("This is a test invite email \n\n\(event?.eventHost) has invited you to join their event", isHTML: false)

        self.present(mc, animated: true, completion: nil)

}

UIBarButtonItem 的一个动作 – 以及所有其他 UIControl 对象 – 可以采用一个参数,该参数是对象本身或没有参数。

关联的方法是

@objc func inviteMethod()

@objc func inviteMethod(_ sender : UIBarButtonItem)

不支持任何自定义参数


你必须这样初始化按钮:

navigationItem.rightBarButtonItem = UIBarButtonItem(title: "\(barButtonItemText)", 
                                                    style: .done, 
                                                    target: self, 
                                                    action: #selector(inviteMethod))