将标题添加到导航栏的左侧

时间:2015-04-29 16:55:16

标签: ios xcode swift uinavigationcontroller navigationbar

是否可以在导航栏的左侧添加标题?我知道如何在中心添加标题但是当我尝试在左侧添加一个标题时我什么也看不见。这是我的代码:

myObject =
  a: 1
  "#{ 1 + 2 }": 3

感谢您的帮助。

3 个答案:

答案 0 :(得分:44)

试试这段代码:

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

这个问题的更强大的解决方案:

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

现在您可以根据需要编辑标签。您可以使用其他字体或文本颜色。

答案 1 :(得分:6)

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

答案 2 :(得分:3)

您可以尝试创建自定义视图,然后创建一个包含该自定义视图的UIBarButtonItem。

自定义视图:

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)