2017-08-28 36 views
0

我使用的是擴展UIViewController這裏面FUNC添加用於調整字體,以適應寬度的標題。navigationItem的手動設定titleview的不神韻:垂直

extesion UIViewController { 
    func setTitleDifferentSizes(title: String){ 
     self.title = title 
     guard let navigationBarHeight: CGFloat = 
self.navigationController?.navigationBar.frame.height else{ 
      return 
     } 

     let tlabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: 
     200.0, height: navigationBarHeight)) 
     tlabel.text = self.title 
     tlabel.textColor = UIColor.white 
     tlabel.font = font24 
     tlabel.backgroundColor = UIColor.clear 
     tlabel.adjustsFontSizeToFitWidth = true 
     self.navigationItem.titleView = tlabel 
    } 
} 

我從這個SO問題,這個解決方案,改變了一點點: How to resize Title in a navigation bar dynamically

現在我的問題是,標題的文本不垂直對齊到其他的導航欄項目,你可以在圖像中看到的,我告訴一個,我剛安裝的稱號,而無需使用上面的方法,以及文本有可能不適合,但它是正確對齊,以及其他圖像是使用上述方法,其中文本適合,但它不對齊。

enter image description here

enter image description here

回答

3

試試這個: -

func setTitleDifferentSizes(title: String){ 
    self.title = title 
    guard let navigationBarHeight: CGFloat = 
     self.navigationController?.navigationBar.frame.height else{ 
      return 
    } 
    let attributedString = NSMutableAttributedString(string: title) 

    let myAttribute = [ NSForegroundColorAttributeName: UIColor.white ,NSFontAttributeName: font24] 

    attributedString.addAttributes(myAttribute, range: NSRange(location: 0, length: attributedString.string.characters.count)) 

    attributedString.addAttributes([NSBaselineOffsetAttributeName:6.0], range:   NSRange(location: 0, length: title.characters.count) 
    ) 

    let tlabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: 
     200.0, height: navigationBarHeight)) 
    tlabel.attributedText = attributedString 
    tlabel.backgroundColor = UIColor.clear 
    tlabel.adjustsFontSizeToFitWidth = true 
    tlabel.minimumScaleFactor = 0.2 
    tlabel.textAlignment = .center 
    self.navigationItem.titleView = tlabel 
} 
如果要調整文本的位置,請更改NSBaselineOffsetAttributeName的浮點值設置垂直對齊

相關問題