How to change the uinavigationbar title's position?

雨燕双飞 提交于 2019-12-05 00:13:23

问题


I've managed to change the navigationbar height by using my own navigationbar, but the title is still centered. I want it to be at the 72px position from the left.

override func sizeThatFits(size: CGSize) -> CGSize {
   return CGSizeMake(UIScreen.mainScreen().bounds.width, 56)
}

I used this to change the height but I didn't find a way to change the position of all the items. I tried to set the frame but I can't. I can't change the position of the button too.

i wanna look like this


回答1:


Create a UIView object add UIButton and UILabel in it to show a similar view. Add this custom view into left bar button item of navigation controller.

An example screen shot to visualise a custom view and related code:

override func viewDidLoad() {
    super.viewDidLoad()

    var customView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 44.0))
    customView.backgroundColor = UIColor.yellow

    var button = UIButton.init(type: .custom)
    button.setBackgroundImage(UIImage(named: "hamburger"), for: .normal)
    button.frame = CGRect(x: 0.0, y: 5.0, width: 32.0, height: 32.0)
    button.addTarget(self, action: #selector(menuOpen(button:)), for: .touchUpInside)
    customView.addSubview(button)

    var marginX = CGFloat(button.frame.origin.x + button.frame.size.width + 5)
    var label = UILabel(frame: CGRect(x: marginX, y: 0.0, width: 65.0, height: 44.0))
    label.text = "Inbox"
    label.textColor = UIColor.white
    label.textAlignment = NSTextAlignment.right
    label.backgroundColor = UIColor.red
    customView.addSubview(label)

    var leftButton = UIBarButtonItem(customView: customView)
    self.navigationItem.leftBarButtonItem = leftButton
}

func menuOpen(button: UIButton) {
    // Handle menu button event here...
}



回答2:


navBar.setTitleVerticalPositionAdjustment(CGFloat(7), forBarMetrics: UIBarMetrics.Default)



回答3:


Another solution is to simply indent the title:

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 72

navigationBar.titleTextAttributes = [
    .foregroundColor: UIColor.purple,
    .paragraphStyle: paragraphStyle
]


来源:https://stackoverflow.com/questions/27539067/how-to-change-the-uinavigationbar-titles-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!