2016-01-22 98 views
5

我有一個包含單個字母的方形UILabel(黃色)。如何調整字體大小以適合UILabel的高度和寬度

enter image description here

我已經使用從this SO answer下面的代碼來調整字體大小,使得其配合到的UILabel:

letterLabel.font = UIFont(name: letterLabel.font.fontName, size: 100) 
letterLabel.adjustsFontSizeToFitWidth = true 
letterLabel.textAlignment = NSTextAlignment.Center 

在截圖可知,字體大小根據寬度。但由於文本只是一個字母,所以我們也需要看高度。我們如何調整字體大小以使高度也在UILabel內?

+0

嘗試使用'letterLabel.sizeToFit()' – b26

回答

-3

嘗試[label sizeToFit][label sizeThatFits:(CGSize)]

+4

此調整標籤的大小,以適應正如被問到的那樣,文字並非相反。 –

0

我沒有找到任何簡單的解決辦法,所以我提出這個擴展:

extension UILabel { 
    func setFontSizeToFill() { 
     let frameSize = self.bounds.size 
     guard frameSize.height>0 && frameSize.width>0 && self.text != nil else {return} 

     var fontPoints = self.font.pointSize 
     var fontSize = self.text!.size(withAttributes: [NSAttributedStringKey.font: self.font.withSize(fontPoints)]) 
     var increment = CGFloat(0) 

     if fontSize.width > frameSize.width || fontSize.height > frameSize.height { 
      increment = -1 
     } else { 
      increment = 1 
     } 

     while true { 
      fontSize = self.text!.size(withAttributes: [NSAttributedStringKey.font: self.font.withSize(fontPoints+increment)]) 
      if increment < 0 { 
       if fontSize.width < frameSize.width && fontSize.height < frameSize.height { 
        fontPoints += increment 
        break 
       } 
      } else { 
       if fontSize.width > frameSize.width || fontSize.height > frameSize.height { 
        break 
       } 
      } 
      fontPoints += increment 
     } 

     self.font = self.font.withSize(fontPoints) 
    } 
} 
相關問題