2015-10-24 161 views
0

這個問題一直在困擾着我很長一段時間。通常當我在故事板中佈置UILabel時,我希望它可以用不同的屏幕寬度進行縮放。我通過創建一個約束將其寬度設置爲與其超級視圖的寬度成比例來使用它。爲什麼autoshrink無法正常工作?

然後,我將文本的大小設置爲300,打開自動收縮並將最小大小設置爲1.理想情況下,這會縮小文本,使其在擬合約束時最大。

但是,這種情況發生。

example

標籤左側自動收縮,但在文本不擴大,以填補(黃色僅僅是唱片公司的背景,而不是另一種觀點)。另一方面,右側的標籤具有固定的大小,但寬度相同,表明字體有更多的增長空間。

怎麼回事?任何修復將不勝感激。

+0

是兩個例子的邊緣到邊緣的標籤嗎?當你有一個很大的單詞時,你能添加兩個更多的截圖嗎? – Korpel

+0

@Korpel標籤不在彩色背景上,顏色是標籤的背景。那有意義嗎? – Joshua

+0

ofc它。你是否嘗試過使用較小的標籤,而不是使用標籤的大小?改爲將其轉換爲UIView,讓標籤佔用較小的空間,然後再試一次? – Korpel

回答

2

經過反覆試驗,我找到了一個解決此問題的方法,即以更小的間隔1縮小字體,以便更好地適應標籤的寬度。

extension UILabel { 
func shrinkToFitWidth(margin: CGFloat?) { 

    // margin parameter will shrink the font by a certain amount more than necessary. 
    // Use this if you want a label with smaller text on a bigger background. Otherwise, use 0. 

    var initialSize : CGSize = self.text!.sizeWithAttributes([NSFontAttributeName : self.font]) 

    if initialSize.width > self.frame.size.width 
    { 
     while initialSize.width > self.frame.size.width 
     { 
      self.font = self.font.fontWithSize(self.font.pointSize - 1) 
      initialSize = self.text!.sizeWithAttributes([NSFontAttributeName : self.font]) 
     } 
    } else { 
     while initialSize.width < self.frame.size.width 
     { 
      self.font = self.font.fontWithSize(self.font.pointSize + 1) 
      initialSize = self.text!.sizeWithAttributes([NSFontAttributeName : self.font]) 
     } 
     // went 1 point too large so compensate here 
     self.font = self.font.fontWithSize(self.font.pointSize - 1) 
    } 

    self.font = self.font.fontWithSize(self.font.pointSize - margin!) 
} 

func shrinkToFitHeight(margin: CGFloat?) { 

    // margin parameter will shrink the font by a certain amount more than necessary. 
    // Use this if you want a label with smaller text on a bigger background. Otherwise, use 0. 

    var initialSize : CGSize = self.text!.sizeWithAttributes([NSFontAttributeName : self.font]) 

    if initialSize.height > self.frame.size.height 
    { 
     while initialSize.height > self.frame.size.height 
     { 
      self.font = self.font.fontWithSize(self.font.pointSize - 1) 
      initialSize = self.text!.sizeWithAttributes([NSFontAttributeName : self.font]) 
     } 
    } else { 
     while initialSize.height < self.frame.size.height 
     { 
      self.font = self.font.fontWithSize(self.font.pointSize + 1) 
      initialSize = self.text!.sizeWithAttributes([NSFontAttributeName : self.font]) 
     } 

     // went 1 point too large so compensate here 
     self.font = self.font.fontWithSize(self.font.pointSize - 1) 
    } 

    self.font = self.font.fontWithSize(self.font.pointSize - margin!) 
} 

注意的是,爲了實現這一點,應該在一個視圖控制器的viewDidLayoutSubviews方法,以便將已應用的約束調用。

乾杯!

相關問題