Change position of UIBarButtonItem in UINavigationBar

后端 未结 20 1516
一个人的身影
一个人的身影 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:09

    • Swift 3
    • custom navigation bar height
    • no title jumping

    Step 1: Set title position using Appearance API. For example, in AppDelegate's didFinishLaunchingWithOptions

    UINavigationBar.appearance().setTitleVerticalPositionAdjustment(-7, for: .default)
    

    Step 2: Subclass UINavigationBar

    class YourNavigationBar: UINavigationBar {
    
        let YOUR_NAV_BAR_HEIGHT = 60
    
        override func sizeThatFits(_ size: CGSize) -> CGSize {
            return CGSize(width: UIScreen.main.bounds.width, 
                         height: YOUR_NAV_BAR_HEIGHT)
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            let navigationItem = self.topItem
    
            for subview in subviews {
                if  subview == navigationItem?.leftBarButtonItem?.customView ||
                    subview == navigationItem?.rightBarButtonItem?.customView {
                    subview.center = CGPoint(x: subview.center.x, y: YOUR_NAV_BAR_HEIGHT / 2)
                }
            }
        }
    }
    

提交回复
热议问题