【问题标题】:Changing UINavigationBar title in iOS8 Swift在 iOS8 Swift 中更改 UINavigationBar 标题
【发布时间】:2014-06-24 09:29:47
【问题描述】:

我以编程方式在我的 Superview 中添加了 UINavigationBar,名为 BaseViewController,它继承了 UIViewController。但是当我尝试为 UINavigationBar 设置标题时。我收到名为 fatal error: Can't unwrap Optional.None

的错误

下面是我的快速课程。 如何解包和更改 UINavigationBar 标题

import UIKit

class BaseViewConroller: UIViewController {
    var navBar:UINavigationBar=UINavigationBar()

    override func viewDidLoad() {
        super.viewDidLoad()
        setNavBarToTheView()
        // Do any additional setup after loading the view.
        navBar.topItem.title="test test"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func setNavBarToTheView()
    {
        navBar.frame=CGRectMake(0, 0, 320, 50)
        navBar.backgroundColor=(UIColor .blackColor())
        self.view .addSubview(navBar)
    }

}

【问题讨论】:

  • 如果可选对象为 nil,则不能解包。这就是你得到错误的原因。始终验证对象为零。正如 Rockey 建议的那样尝试 self.title

标签: uinavigationbar swift ios8


【解决方案1】:

将您的navBar.topItem.title="test test" 替换为self.title="test test"。干杯!!

【讨论】:

    【解决方案2】:
    UILabel *labelTitle = UILabel(frame: CGRectZero);
    labelTitle.text = "Title";
    labelTitle.text.textAlignment = NSTextAlignment.Center
    self.navigationItem.titleView = labelTitle;
    

    我有这段代码...希望对您有所帮助。

    【讨论】:

    • 致命错误:无法解开 Optional.None 相同的错误,更喜欢 swift 代码
    【解决方案3】:

    实用地更改导航栏文本。只需调用下面写的函数setNavigationBarTitleText("WhateverTextNeeded")。我假设您已经配置了 UINavigationBar。

    var navBar = UINavigationBar(frame: CGRectZero)
    
    func setNavigationBarTitleText(text: String){
        let titleLabel = UILabel(frame: CGRectMake(0, 0, view.frame.size.width - 120, 44))
        titleLabel.backgroundColor = UIColor.clearColor()
        titleLabel.numberOfLines = 2
        titleLabel.font = UIFont(name: UIConfig.Fonts.OswaldRegular,  size: 16)
        titleLabel.textAlignment = NSTextAlignment.Center
        titleLabel.text = text.uppercaseString
        self.navBar.topItem?.titleView = titleLabel
    }
    

    我希望这会有所帮助。

    【讨论】:

      【解决方案4】:

      您可以使用此代码来转换您的导航栏。

       self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "imageName")
          self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "imageName")
          self.navigationController?.navigationBar.backItem?.title = ""
          self.navigationController?.navigationBar.tintColor = UIColor.white
          self.title = "Title"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-06
        • 1970-01-01
        • 2015-10-04
        • 1970-01-01
        • 2012-05-25
        • 1970-01-01
        • 2014-06-01
        • 1970-01-01
        相关资源
        最近更新 更多