ios 如何在 Swift 中为 UIBarButtonItem 设置操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24641350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:16:53  来源:igfitidea点击:

How to set the action for a UIBarButtonItem in Swift

iosswiftactionuibarbuttonitem

提问by kmiklas

How can the action for a custom UIBarButtonItem in Swift be set?

如何设置 Swift 中自定义 UIBarButtonItem 的操作?

The following code successfully places the button in the navigation bar:

以下代码成功将按钮放置在导航栏中:

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:nil)
self.navigationItem.rightBarButtonItem = b

Now, I would like to call func sayHello() { println("Hello") }when the button is touched. My efforts so far:

现在,我想func sayHello() { println("Hello") }在触摸按钮时调用。我到目前为止的努力:

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:sayHello:)
// also with `sayHello` `sayHello()`, and `sayHello():`

and..

和..

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:@selector(sayHello:))
// also with `sayHello` `sayHello()`, and `sayHello():`

and..

和..

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:@selector(self.sayHello:))
// also with `self.sayHello` `self.sayHello()`, and `self.sayHello():`

Note that sayHello()appears in the intellisense, but does not work.

请注意,sayHello()出现在智能感知中,但不起作用。

Thanks for your help.

谢谢你的帮助。

EDIT: For posterity, the following works:

编辑:对于后代,以下作品:

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:"sayHello")

回答by drewag

As of Swift 2.2, there is a special syntax for compiler-time checked selectors. It uses the syntax: #selector(methodName).

从 Swift 2.2 开始,编译器时检查的选择器有一种特殊的语法。它使用语法:#selector(methodName).

Swift 3 and later:

Swift 3 及更高版本:

var b = UIBarButtonItem(
    title: "Continue",
    style: .plain,
    target: self,
    action: #selector(sayHello(sender:))
)

func sayHello(sender: UIBarButtonItem) {
}

If you are unsure what the method name should look like, there is a special version of the copy command that is very helpful. Put your cursor somewhere in the base method name (e.g. sayHello) and press Shift+Control+Option+C. That puts the ‘Symbol Name' on your keyboard to be pasted. If you also hold Commandit will copy the ‘Qualified Symbol Name' which will include the type as well.

如果您不确定方法名称应该是什么样子,那么复制命令的特殊版本非常有用。将光标放在基本方法名称中的某个位置(例如 sayHello),然后按 Shift+ Control+ Option+ C。这会将“符号名称”放在要粘贴的键盘上。如果您还持有Command它,它将复制“合格符号名称”,其中也将包含类型。

Swift 2.3:

斯威夫特 2.3:

var b = UIBarButtonItem(
    title: "Continue",
    style: .Plain,
    target: self,
    action: #selector(sayHello(_:))
)

func sayHello(sender: UIBarButtonItem) {
}

This is because the first parameter name is not required in Swift 2.3 when making a method call.

这是因为在 Swift 2.3 中进行方法调用时不需要第一个参数名称。

You can learn more about the syntax on swift.org here: https://swift.org/blog/swift-2-2-new-features/#compile-time-checked-selectors

您可以在此处了解有关 swift.org 语法的更多信息:https://swift.org/blog/swift-2-2-new-features/#compile-time-checked-selectors

回答by norbDEV

Swift 4/5 example

Swift 4/5 示例

button.action = #selector(buttonClicked(sender:))

@objc func buttonClicked(sender: UIBarButtonItem) {

}

回答by Anurag Bhakuni

May this one help a little more

愿这个帮助多一点

Let suppose if you want to make the bar button in a separate file(for modular approach) and want to give selector back to your viewcontroller, you can do like this :-

假设您想在单独的文件中制作条形按钮(用于模块化方法)并希望将选择器返回给您的视图控制器,您可以这样做:-

your Utility File

您的实用程序文件

class GeneralUtility {

    class func customeNavigationBar(viewController: UIViewController,title:String){
        let add = UIBarButtonItem(title: "Play", style: .plain, target: viewController, action: #selector(SuperViewController.buttonClicked(sender:)));  
      viewController.navigationController?.navigationBar.topItem?.rightBarButtonItems = [add];
    }
}

Then make a SuperviewController class and define the same function on it.

然后创建一个 SuperviewController 类并在其上定义相同的函数。

class SuperViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
            // Do any additional setup after loading the view.
    }
    @objc func buttonClicked(sender: UIBarButtonItem) {

    }
}

and In our base viewController(which inherit your SuperviewController class) override the same function

并在我们的基本 viewController(继承您的 SuperviewController 类)中覆盖相同的功能

import UIKit

class HomeViewController: SuperViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(_ animated: Bool) {
        GeneralUtility.customeNavigationBar(viewController: self,title:"Event");
    }

    @objc override func buttonClicked(sender: UIBarButtonItem) {
      print("button clicked")    
    } 
}

Now just inherit the SuperViewController in whichever class you want this barbutton.

现在只需在你想要这个 barbutton 的任何类中继承 SuperViewController。

Thanks for the read

感谢阅读

回答by Mahesh

Swift 5

斯威夫特 5

if you have created UIBarButtonItemin Interface Builder and you connected outlet to item and want to bind selector programmatically.

如果您已UIBarButtonItem在 Interface Builder 中创建并将插座连接到项目并希望以编程方式绑定选择器。

Don't forget to set target and selector.

不要忘记设置目标和选择器。

addAppointmentButton.action = #selector(moveToAddAppointment)
addAppointmentButton.target = self

@objc private func moveToAddAppointment() {
     self.presenter.goToCreateNewAppointment()
}