xcode 在导航栏左侧添加标题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29949969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding a title to the left side of the navigation bar
提问by Brejuro
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.
感谢您的帮助。
回答by Vasyl Khmil
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.
现在您可以根据需要编辑标签。您可以使用其他字体或文本颜色。
回答by Yestay Muratov
navigationController?.navigationBar.isTranslucent = false
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
回答by Alex
You could try creating a custom view, and then create a UIBarButtonItem with that custom view in it.
您可以尝试创建一个自定义视图,然后创建一个包含该自定义视图的 UIBarButtonItem。
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)