How do I left align the title of a navigation bar in Xcode?

前端 未结 2 914
一个人的身影
一个人的身影 2020-12-15 23:05

I\'ve been trying the following in order to get the title of a navigation bar left aligned:

In the AppDelegate.swift file:

func applicat         


        
相关标签:
2条回答
  • 2020-12-15 23:38

    You can use the navigationItems titleView to add a UILabel with left alignment and then set its frame using auto layout like this:

    let label = UILabel()
    label.text = "Title Label"
    label.textAlignment = .left
    self.navigationItem.titleView = label
    label.translatesAutoresizingMaskIntoConstraints = false
    label.superview?.addConstraint(NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: label.superview, attribute: .centerX, multiplier: 1, constant: 0))
    label.superview?.addConstraint(NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal, toItem: label.superview, attribute: .width, multiplier: 1, constant: 0))
    label.superview?.addConstraint(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: label.superview, attribute: .centerY, multiplier: 1, constant: 0))
    label.superview?.addConstraint(NSLayoutConstraint(item: label, attribute: .height, relatedBy: .equal, toItem: label.superview, attribute: .height, multiplier: 1, constant: 0))
    
    0 讨论(0)
  • 2020-12-15 23:44
    let label = UILabel()
    label.textColor = UIColor.white
    label.text = "TCO_choose_reminder".localized;
    self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: label)
    

    I init a UIBarButtonItem with the constructor that gets a UIView and set my desired label as parameter to get the following.

    Edit:

    If you do not want the back button to be removed. Set the following flag.

    self.navigationItem.leftItemsSupplementBackButton = true
    

    Keep in mind that having a label + Back button (with title) would not look cool.In this case I replace the default back button with an arrow asset.

    0 讨论(0)
提交回复
热议问题