我在Superview中以编程方式添加了名为BaseViewController的UINavigationBar,它继承了UIViewController。但是当我尝试为UINavigationBar设置标题时。我收到名为致命错误的错误:无法解包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)
}
}
答案 0 :(得分:28)
将navBar.topItem.title="test test"
替换为self.title="test test"
。干杯!!
答案 1 :(得分:0)
UILabel *labelTitle = UILabel(frame: CGRectZero);
labelTitle.text = "Title";
labelTitle.text.textAlignment = NSTextAlignment.Center
self.navigationItem.titleView = labelTitle;
我有这段代码......我希望,这可以帮助你。
答案 2 :(得分:0)
以实际方式更改导航栏文本。只需调用下面写的func 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
}
我希望这会有所帮助。
答案 3 :(得分:0)
您可以使用此代码转换导航栏。
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"