2015-04-05 92 views
0

我想設置一個導航欄標題,但是我迄今試過的每種方法都會將標題移動得太遠,或者視圖根本無法加載並導致應用程序崩潰。這是我最近的嘗試(應用程序崩潰)右側和左側酒吧項目的中心導航欄標題?

let rightItemSize = self.navigationItem.rightBarButtonItem?.width 
    let leftItemSize = self.navigationItem.leftBarButtonItem?.width 

    let navWidth = self.navigationController?.navigationBar.frame.size.width 
    let navHeight = self.navigationController?.navigationBar.frame.size.height 


    let titleWidth = navWidth! - (rightItemSize! + leftItemSize!) 

    let requiredPadding = rightItemSize! - leftItemSize! 

    var titleViewToAdd = UIView(frame: CGRectMake(0, 0, titleWidth, navHeight!)) 
    var label = UILabel(frame: CGRectMake(requiredPadding, 0, titleWidth - requiredPadding, navHeight!)) 

    label.backgroundColor = UIColor.redColor() 
    label.font = UIFont.boldSystemFontOfSize(14.0) 
    label.textColor = UIColor.blackColor() 
    label.numberOfLines = 1 
    label.textAlignment = NSTextAlignment.Center 

    label.text = "\(albumsArtist)" 

    titleViewToAdd.addSubview(label) 
    self.navigationItem.titleView = titleViewToAdd 

如果我使用self.navigationItem.title =「\(albumsArtist)」。文本是居中,工作很好,但最終我想有兩行文本,這種方法將無法正常工作。

我知道有與答案就在這裏類似的問題,但所有的人的我已經看過一直是Objective-C和沒有工作這麼好,當我試圖將其轉換爲斯威夫特。

非常感謝!

回答

3

管理使它與此工作!

var label = UILabel(frame: CGRectMake(10.0, 0.0, 50.0, 40.0)) 
    label.backgroundColor = UIColor.redColor() 
    label.font = UIFont.boldSystemFontOfSize(14.0) 

    let string = albumsArtist.substringToIndex(min(25, albumsArtist.length)) 
    label.numberOfLines = 2 
    label.text = "\(string)\nXX tracks, X mins" 
    label.textColor = UIColor.blackColor() 
    label.sizeToFit() 
    label.textAlignment = NSTextAlignment.Center 

    self.navigationItem.titleView = label 
相關問題