2015-02-11 25 views
2

我試圖將UIButton作爲titleView用於我的UINavigationItem。這是我的代碼,但它不起作用。標題完全空白。UIButton as UINavigationItem titleView

override func viewDidLoad() { 
    super.viewDidLoad() 

    let titleButton = UIButton() 
    titleButton.titleLabel?.font = UIFont(name: "HelveticaNeue-Medium", size: 16) 
    titleButton.titleLabel?.textAlignment = NSTextAlignment.Center; 
    titleButton.titleLabel?.text = "My Custom Title" 
    titleButton.titleLabel?.sizeToFit() 

    self.navigationItem.titleView = titleButton 
} 

下面是失蹤標題的屏幕截圖。

screenshot

+0

調試並檢查它是否有實際的幀 – rcat24 2015-02-11 15:00:11

回答

3

要設置按鈕,你不應該直接設置標籤的文本是標題,你應該配置按鈕設置標題使用func setTitle(_ title: String?, forState state: UIControlState)特定狀態。

通常,您將標題設置爲.Normal,然後將應用於所有狀態(作爲默認值)。

+0

謝謝!什麼菜鳥的錯誤。 :) – Fenda 2015-02-11 15:18:38

4

如果您使用的是故事板,則可以將UIButton拖動到titleView。如果Interface Builder不允許你這樣做,那是因爲你需要先將UINavigationItem拖到導航欄中,然後拖動視圖,如UIButton

+1

哦,快點!我不知道這甚至是可能的。我會接受其他答案,因爲它直接回答了問題中代碼的錯誤。不過,我會走這條路,因爲它更有意義。 – Fenda 2015-02-11 15:27:14

+0

我很高興它幫助@Fenda! Interface Builder越來越強大,但在沉默中;) – Gorka 2015-02-11 15:28:21

相關問題