Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

ios - Change Right Bar Button Items on Current Screen

I have spent all day trying to figure this out and I'm beyond frustrated.

I have a navigation stack and on each screen, based on the content of the screen, I need to hide/show some of the right bar button items. But no matter what I do, the items are changing on the previous screen on the stack, not on the current screen.

My view controllers are all pushed onto a navigation controller. And each view controller can instantiate another view controller and push onto the navigation stack.

let vc = UnifiedArticleViewController()
        
navigationController?.pushViewController(vc, animated: true)

I have tried the following:

navigationController?.navigationBar.topItem?.rightBarButtonItems = [arrayOfBarButtonItems]

and:

navigationItem.rightBarButtonItems = [arrayOfBarButtonItems]

as well as a variety of other suggestions I've gotten from various stack overflow suggestions.

I have been able to change the title of screens using:

navigationController?.navigationBar.topItem?.title = "New Title Here"

and that works perfectly. What am I doing wrong?

question from:https://stackoverflow.com/questions/65927595/change-right-bar-button-items-on-current-screen

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Set the leftBarButtonItems or rightBarButtonItems from the controller you're wanting to set the button(s) on that is in the navigation controller's view stack.

class ViewController: UIViewController {
    override func viewDidLoad() {
        let leftButton = UIBarButtonItem(title: "Left", style: .done, target: self, action: #selector(leftButtonPressed(_:)))
        self.navigationItem.leftBarButtonItems = [leftButton]

        let rightButton = UIBarButtonItem(title: "Right", style: .done, target: self, action: #selector(rightButtonPressed(_:)))
        self.navigationItem.rightBarButtonItems = [rightButton]
    }
    @objc func leftButtonPressed(_ sender: UIBarButtonItem) {

    }
    @objc func rightButtonPressed(_ sender: UIBarButtonItem) {

    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...