Can't set titleView in the center of navigation bar because back button

前端 未结 10 1560
情话喂你
情话喂你 2020-12-08 02:25

I\'m using an image view to display an image in my nav bar. The problem is that I can\'t set it to the center correctly because of the back button. I checked the related que

10条回答
  •  我在风中等你
    2020-12-08 02:55

    I created a custom UINavigationController that after dropping in, the only thing you have to do is call showNavBarTitle(title:font:) when you want to show and removeNavBarTitle() when you want to hide:

    class NavigationController: UINavigationController {
    
        private static var mTitleFont = UIFont(name:  , size: )!
        private static var mNavBarLabel: UILabel = {
    
            let x: CGFloat = 60
            let y: CGFloat = 7
            let label = UILabel(frame: CGRect(x: x, y: y, width: UIScreen.main.bounds.size.width - 2 * x, height: 44 - 2 * y))
    
            label.adjustsFontSizeToFitWidth = true
            label.minimumScaleFactor = 0.5
            label.font = NavigationController.mTitleFont
            label.numberOfLines = 0
            label.textAlignment = .center
    
            return label
        }()
    
        func showNavBarLabel(title: String, font: UIFont = mTitleFont) {
            NavigationController.mNavBarLabel.text = title
            NavigationController.mNavBarLabel.font = font
            navigationBar.addSubview(NavigationController.mNavBarLabel)
        }
    
        func removeNavBarLabel() {
            NavigationController.mNavBarLabel.removeFromSuperview()
        }
    }
    

    I find the best place to call showNavBarTitle(title:font:) and removeNavBarTitle() are in the view controller's viewWillAppear() and viewWillDisappear() methods, respectively:

    class YourViewController: UIViewController {
    
        func viewWillAppear() {
            (navigationController as! NavigationController).showNavBarLabel(title: "Your Title")
        }
    
        func viewWillDisappear() {
            (navigationController as! NavigationController).removeNavBarLabel()
        }
    }
    

提交回复
热议问题