2016-11-10 125 views
0

我試圖通過設置爲導航欄標題的標籤(UILabel)將UIViewController子類化。我不想將名稱設置爲self.title,而是使用屬性字符串來設置標題。使用NavigationBar子類UIViewController標題

class BasicViewController: UIViewController { 
    var titleString = "" 

    func setup() { 
     //self.title = titleString 
     let navBar = navigationController!.navigationBar 
     navBar.barTintColor = UIColor.redColor() 
     let atext = NSMutableAttributedString(string: titleString) 
     atext.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: NSMakeRange(0, atext.length)) 
     atext.addAttribute(NSStrokeColorAttributeName, value: UIColor.yellowColor(), range: NSMakeRange(0, atext.length)) 
     atext.addAttribute(NSStrokeWidthAttributeName, value: NSNumber.init(float: -1.0), range: NSMakeRange(0, atext.length)) 
     let titleLabel:UILabel = UILabel.init(frame: CGRectMake(50, 3, 220, 44)) 
     titleLabel.attributedText = atext 
     titleLabel.textAlignment = NSTextAlignment.Center 
     titleLabel.font = UIFont(name: "Helvetica", size: 24.0) 
    } 
} 

class HomeViewController: BasicViewController { 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     titleString = "My App" 
     setup() 
    } 
} 

如果我運行此代碼,我會得到一個空標題。我究竟做錯了什麼?謝謝。

+0

是否將'titleLabel'添加到任何視圖? 你可以使用下面的didSet方法btw,所以你不必在設置字符串後運行'setup()'。 '''VAR titleString = 「」{ didSet { 讓導航欄= navigationController!.navigationBar (...) }} ''' – Houwert

+0

titleLbel可以被添加到導航欄,如果我直接插入線使用HomeViewController的viewDidLoad在setup()內部的代碼。 –

回答

0

我看不到你正在設置的位置self.navigationItem.titleView = titleLabel

相關問題