Adding a title to the left side of the navigation bar

旧街凉风 提交于 2019-12-20 10:36:13

问题


Is it possible to add a title to the left side of the navigation bar? I know how I can add a title in the center but when I try to add one to the left side I see nothing. This is the code I have:

self.navigationItem.leftBarButtonItem?.title = "Elapsed Time: 0:00"

Thank you for the help.


回答1:


Try this code:

let leftItem = UIBarButtonItem(title: "Title",
                                   style: UIBarButtonItemStyle.plain,
                                   target: nil,
                                   action: nil)
    leftItem.isEnabled = false
    self.navigationItem.leftBarButtonItem = leftItem

More powerful solution of this problem:

let longTitleLabel = UILabel()
    longTitleLabel.text = "Long long long long long long title"
    longTitleLabel.font = ................
    longTitleLabel.sizeToFit()

    let leftItem = UIBarButtonItem(customView: longTitleLabel)
    self.navigationItem.leftBarButtonItem = leftItem

Now you just can edit label as you want. You can use another font or text color.




回答2:


navigationController?.navigationBar.isTranslucent = false

    let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width - 32, height: view.frame.height))
    titleLabel.text = "  Home"
    titleLabel.textColor = UIColor.white
    titleLabel.font = UIFont.systemFont(ofSize: 20)
    navigationItem.titleView = titleLabel



回答3:


You could try creating a custom view, and then create a UIBarButtonItem with that custom view in it.

Custom view:

var button = UIButton(frame: CGRectMake(0, 0, 44, 44))
var label = UILabel(frame: CGRectMake(0, 0, 44, 14)) // adjust as you see fit

label.text = "Label test"
label.textAlignment = NSTextAlignment.Left

button.addSubview(label)

// Add it to your left bar button

self.navigationItem.leftBarButtonItems = [barButtonNegativeSpacer, UIBarButtonItem(customView: button)


来源:https://stackoverflow.com/questions/29949969/adding-a-title-to-the-left-side-of-the-navigation-bar

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