How to set the action for a UIBarButtonItem in Swift

前端 未结 5 2136
余生分开走
余生分开走 2020-12-12 19:51

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 = UIB         


        
5条回答
  •  情书的邮戳
    2020-12-12 20:50

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

提交回复
热议问题