【问题标题】:Adding a title to the left side of the navigation bar在导航栏左侧添加标题
【发布时间】:2015-07-09 02:34:10
【问题描述】:

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

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

感谢您的帮助。

【问题讨论】:

    标签: ios xcode swift uinavigationcontroller navigationbar


    【解决方案1】:

    试试这个代码:

    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
    

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

    【讨论】:

    • @Alex 因为在另一种情况下,您会看到点击动画。它是一个按钮,并且有点击动画。
    • 明白了,有道理。谢谢
    • 它有效,但它是灰色的有什么原因吗?是因为没有启用吗?
    • @Brejuro 是的,正因为如此,如果你愿意,我可以为这个问题写另一个更强大的解决方案
    • @Vasyl 你介意帮我解决这个问题吗?那太好了。
    【解决方案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】:

      您可以尝试创建一个自定义视图,然后在其中创建一个包含该自定义视图的 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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-15
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 2019-05-20
        • 1970-01-01
        • 2016-06-22
        相关资源
        最近更新 更多