Change position of UIBarButtonItem in UINavigationBar

后端 未结 20 1502
一个人的身影
一个人的身影 2020-11-27 10:31

How can I change the position of a UIBarButtonItem in a UINavigationBar? I would like my button to be about 5px higher than its normal position.

20条回答
  •  温柔的废话
    2020-11-27 11:18

    As @Anomie said, we need to subclass UINavigationBar, and override layoutSubviews().

    This will place all right bar button items firmly attached to the right side of the navigation bar (as opposed to being slightly left-adjusted by default):

    class AdjustedNavigationBar: UINavigationBar {
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            if let rightItems = topItem?.rightBarButtonItems where rightItems.count > 1 {
                for i in 0..

    The only place to set the UINavigationBar property of UINavigationController is in its init(), like so:

    let controllerVC = UINavigationController(navigationBarClass: AdjustedNavigationBar.self, toolbarClass: nil)
    controllerVC.viewControllers = [UIViewController()]
    

    The second line sets the root view controller of UINavigationController. (Since we cannot set it via init(rootViewController:)

提交回复
热议问题