changing nav bar item programmatically in Swift

后端 未结 1 1813
挽巷
挽巷 2021-02-15 13:07

So I\'m trying to change the left nav bar button item in viewWillAppear (the item needs to be changed back and forth, so viewDidLoad won\'t work). I have the following code in v

相关标签:
1条回答
  • 2021-02-15 13:33

    The following code should work:

    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let refreshButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: "buttonMethod")
            navigationItem.leftBarButtonItem = refreshButton
    
            navigationController?.navigationBar.barTintColor = UIColor.greenColor()
            title = "Search result"
        }
    
        func buttonMethod() {
            print("Perform action")
        }
    
    }
    

    If you really need to perform it in viewWillAppear:, here is the code:

    import UIKit
    
    class ViewController: UIViewController {
    
        var isLoaded = false
    
        override func viewWillAppear(animated: Bool) {
            super.viewWillAppear(animated)
    
            if !isLoaded {
                let refreshButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: "buttonMethod")
                navigationItem.leftBarButtonItem = refreshButton
                isLoaded = true
    
                navigationController?.navigationBar.barTintColor = UIColor.greenColor()
                title = "Search result"
            }
        }
    
        func buttonMethod() {
            print("Perform action")
        }
    
    }
    

    You can learn more about the navigationItem properties with this previous question.

    0 讨论(0)
提交回复
热议问题