2014-06-24 18 views
7

Ho aggiunto UINavigationBar nel mio Superview, chiamato BaseViewController, che eredita UIViewController. Ma quando provo a impostare un titolo su UINavigationBar. Ottengo l'errore chiamato errore irreversibile : Impossibile scartare Optional.NoneModifica titolo UINavigationBar in iOS8 Swift

Di seguito è la mia classe veloce. Come può scartare e cambiare il titolo 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

se l'oggetto facoltativo è nullo, non è possibile scartarlo. Ecco perché ottieni l'errore. Convalida sempre gli oggetti per zero. Come suggerito da Rockey, provare l'errore fatidico di self.title –

risposta

28

Sostituire navBar.topItem.title="test test" con self.title="test test". Saluti!!

+0

Facile e indolore. – Josh

0
UILabel *labelTitle = UILabel(frame: CGRectZero); 
labelTitle.text = "Title"; 
labelTitle.text.textAlignment = NSTextAlignment.Center 
self.navigationItem.titleView = labelTitle; 

ho questo codice ... mi auguro, che posso aiutare.

+3

: Impossibile scartare Opzionale.Nessuno Stesso errore e preferisco il codice rapido – Ashan

0

Per modificare pragmaticamente il testo della barra di navigazione. Basta chiamare la funzione setNavigationBarTitleText("WhateverTextNeeded") scritta di seguito. Suppongo che tu abbia già configurato la tua 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 
} 

Spero che questo aiuti.

0

È possibile utilizzare questo codice per trasformare la barra di navigazione.

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" 
Problemi correlati