[ios] How to set the action for a UIBarButtonItem in Swift

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

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:

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.

Thanks for your help.

EDIT: For posterity, the following works:

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

This question is related to ios swift action uibarbuttonitem

The answer is


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

Swift 3 and later:

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 Command it will copy the ‘Qualified Symbol Name’ which will include the type as well.

Swift 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.

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 4/5 example

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

@objc func buttonClicked(sender: UIBarButtonItem) {
        
}

Swift 5

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

Don't forget to set target and selector.

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

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

Swift 5 & iOS 13+ Programmatic Example

  1. You must mark your function with @objc, see below example!
  2. No parenthesis following after the function name! Just use #selector(name).
  3. private or public doesn't matter; you can use private.

Code Example

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    let menuButtonImage = UIImage(systemName: "flame")
    let menuButton = UIBarButtonItem(image: menuButtonImage, style: .plain, target: self, action: #selector(didTapMenuButton))
    navigationItem.rightBarButtonItem = menuButton
}

@objc public func didTapMenuButton() {
    print("Hello World")
}

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.

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

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.

Thanks for the read


Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to action

Adding form action in html in laravel How to set the action for a UIBarButtonItem in Swift Execution order of events when pressing PrimeFaces p:commandButton Using Cookie in Asp.Net Mvc 4 Get controller and action name from within controller? HTML form action and onsubmit issues How to pass value from <option><select> to form action Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id} Single line if statement with 2 actions How do I use two submit buttons, and differentiate between which one was used to submit the form?

Examples related to uibarbuttonitem

UIBarButtonItem in navigation bar programmatically? Change color of Back button in navigation bar How to set image for bar button with swift? How to set the action for a UIBarButtonItem in Swift Removing the title text of an iOS UIBarButtonItem How do I show/hide a UIBarButtonItem? Add button to navigationbar programmatically Setting action for back button in navigation controller