2012-01-10 114 views
35

我見過一堆改變UILabel大小的例子。如何設置字體大小以填充UILabel高度?

以下是我想要做的: 更改字體大小,以便文本在新高度內儘可能大。

任何線索?

+1

我剛剛意識到執行二進制或其他搜索是完全沒有必要的。您只需要使用**比率搜索**重複(幾次)。它很容易。我將粘貼完整的代碼作爲答案。 – Fattie 2016-05-17 13:29:04

+1

..競爭解決方案2016年http://stackoverflow.com/a/372​​77874/294884非常簡單的代碼。 – Fattie 2016-05-18 13:05:32

回答

15

編輯:檢查Joel Fischer的偉大答案,以編程方式獲得正確的大小!

您可以將字體設置爲自動填充標籤的大小,並且可以選擇不低於最小字體大小。只需將adjustsFontSizeToFitWidth設置爲YES.如果您需要更多信息,請查看UILabel Class Reference

儘管布爾值被稱爲「adjustsFontSizeToFitWidth」,但它確實意味着標籤高度的最大尺寸,它將保留在標籤的一行(或者您指定的多行)上。

+1

設置一個非常大的字體,這個屬性將比代碼容易得多。 – 2012-01-11 00:40:07

+0

準確地說,你不需要擔心在編程後再次調整字體大小。 – DGund 2012-01-11 00:45:38

+0

嘗試adjustsFontSizeToFitWidth,但沒有任何事情發生在我的標籤上。行數= 1。我使用這個代碼:'[clockLabel sizeToFit]; CGRect newFrame = clockLabel.frame; newFrame.size.height = screenWidth * 0.8; clockLabel.frame = newFrame; clockLabel.adjustsFontSizeToFitWidth = YES; ' – wayneh 2012-01-11 18:57:09

-7

是的,轉到界面生成器(您的.xib文件),然後轉到屬性檢查器右側的第三個選項卡,您可以在其中設置字體的大小!

28

以下是我如何做到的,因爲DGund的答案對我無效,它適合寬度,但我希望它適合高度。

+ (UIFont *)findAdaptiveFontWithName:(NSString *)fontName forUILabelSize:(CGSize)labelSize withMinimumSize:(NSInteger)minSize 
{ 
    UIFont *tempFont = nil; 
    NSString *testString = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 

    NSInteger tempMin = minSize; 
    NSInteger tempMax = 256; 
    NSInteger mid = 0; 
    NSInteger difference = 0; 

    while (tempMin <= tempMax) { 
     mid = tempMin + (tempMax - tempMin)/2; 
     tempFont = [UIFont fontWithName:fontName size:mid]; 
     difference = labelSize.height - [testString sizeWithFont:tempFont].height; 

     if (mid == tempMin || mid == tempMax) { 
      if (difference < 0) { 
       return [UIFont fontWithName:fontName size:(mid - 1)]; 
      } 

      return [UIFont fontWithName:fontName size:mid]; 
     } 

     if (difference < 0) { 
      tempMax = mid - 1; 
     } else if (difference > 0) { 
      tempMin = mid + 1; 
     } else { 
      return [UIFont fontWithName:fontName size:mid]; 
     } 
    } 

    return [UIFont fontWithName:fontName size:mid]; 
} 

這將需要的字體名稱,大小(它沒有成爲一個UILabel,從理論上說,但我總是一個UILabel用它)和最小尺寸(您也可以使用最高大小,只需用最大尺寸參數替換256)。這將基本上測試最小和最大字體大小之間的每種字體大小,並返回位於或低於目標高度的字體大小。

用法是自我解釋,但看起來是這樣的:

self.myLabel.font = [self findAdaptiveFontWithName:@"HelveticaNeue-UltraLight" forUILabelSize:self.myLabel.frame.size withMinimumSize:30]; 

您也可以在此UIFont類方法類別(這是我做的)。

編輯:關於建議,我刪除了for循環,花了一點時間使它更有效的二進制搜索例程。我做了一些檢查,以確保字體最終適合標籤內容。在最初的測試中,它似乎工作。

+4

您可能想要通過使用二進制搜索例程來加速此算法。 – 2013-07-12 21:20:30

+0

@RobvanderVeer我看到的問題是我不知道我正在尋找的確切的「解決方案」。它可以是高度的大小,也可以小一些,確實比標籤高度大一個,但我沒有想過如何將它變成更多高效的算法。所以,雖然他們在技術上已經排序,但在測試之前我沒有這些值。二進制搜索會讓我比手動循環更接近。 – 2013-07-15 14:23:11

+1

@RobvanderVeer添加了二進制搜索。如果您發現任何問題,請告知我。 – 2013-07-15 15:09:47

4

這很大程度上借鑑了喬爾菲捨爾的回答。他的回答只是考慮到標籤的高度 - 我已經做了一些改動,以考慮到標籤寬度以及(給定的輸入字符串),這是我想要的東西:

typedef enum 
{ 
    kDimensionHeight, 
    kDimensionWidth, 
} DimensionType; 

@implementation UIFont (AdaptiveFont) 

+ (UIFont *)_adaptiveFontWithName:(NSString *)fontName minSize:(NSInteger)minSize labelDimension:(CGFloat)labelDimension testString:(NSString *)testString dimension:(DimensionType)dimension 
{ 
    UIFont *tempFont = nil; 
    NSInteger tempMin = minSize; 
    NSInteger tempMax = 256; 
    NSInteger mid = 0; 
    NSInteger difference = 0; 
    CGFloat testStringDimension = 0.0; 

    while (tempMin <= tempMax) { 
     @autoreleasepool { 
      mid = tempMin + (tempMax - tempMin)/2; 
      tempFont = [UIFont fontWithName:fontName size:mid]; 

      // determine dimension to test 
      if (dimension == kDimensionHeight) { 
       testStringDimension = [testString sizeWithFont:tempFont].height; 
      } else { 
       testStringDimension = [testString sizeWithFont:tempFont].width; 
      } 
      difference = labelDimension - testStringDimension; 

      if (mid == tempMin || mid == tempMax) { 
       if (difference < 0) { 
        return [UIFont fontWithName:fontName size:(mid - 1)]; 
       } 
       return [UIFont fontWithName:fontName size:mid]; 
      } 

      if (difference < 0) { 
       tempMax = mid - 1; 
      } else if (difference > 0) { 
       tempMin = mid + 1; 
      } else { 
       return [UIFont fontWithName:fontName size:mid]; 
      } 
     } 
    } 
    return [UIFont fontWithName:fontName size:mid]; 
} 

+ (UIFont *)adaptiveFontWithName:(NSString *)fontName minSize:(NSInteger)minSize labelSize:(CGSize)labelSize string:(NSString *)string 
{ 
    UIFont *adaptiveFont = nil; 
    NSString *testString = nil; 

    // get font, given a max height 
    testString = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
    UIFont *fontConstrainingHeight = [UIFont _adaptiveFontWithName:fontName minSize:minSize labelDimension:labelSize.height testString:testString dimension:kDimensionHeight]; 
    CGSize boundsConstrainingHeight = [string sizeWithFont:fontConstrainingHeight]; 
    CGSize boundsConstrainingWidth = CGSizeZero; 

    // if WIDTH is fine (while constraining HEIGHT), return that font 
    if (boundsConstrainingHeight.width <= labelSize.width) { 
     adaptiveFont = fontConstrainingHeight; 
    } else { 
     // get font, given a max width 
     // i.e., fontConstrainingWidth 
     testString = string; 
     adaptiveFont = [UIFont _adaptiveFontWithName:fontName minSize:minSize labelDimension:labelSize.width testString:testString dimension:kDimensionWidth]; 

     // TEST comparison 
     boundsConstrainingWidth = [string sizeWithFont:adaptiveFont]; 
    } 
    return adaptiveFont; 
} 
12

根據高度的文本適應我的標籤我有適應喬爾的方法來迅速

func optimisedfindAdaptiveFontWithName(fontName:String, label:UILabel!, minSize:CGFloat,maxSize:CGFloat) -> UIFont! 
{ 

    var tempFont:UIFont 
    var tempHeight:CGFloat 
    var tempMax:CGFloat = maxSize 
    var tempMin:CGFloat = minSize 

    while (ceil(tempMin) != ceil(tempMax)){ 
     let testedSize = (tempMax + tempMin)/2 


     tempFont = UIFont(name:fontName, size:testedSize) 
     let attributedString = NSAttributedString(string: label.text!, attributes: [NSFontAttributeName : tempFont]) 

     let textFrame = attributedString.boundingRectWithSize(CGSize(width: label.bounds.size.width, height: CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin , context: nil) 

     let difference = label.frame.height - textFrame.height 
     println("\(tempMin)-\(tempMax) - tested : \(testedSize) --> difference : \(difference)") 
     if(difference > 0){ 
      tempMin = testedSize 
     }else{ 
      tempMax = testedSize 
     } 
    } 


    //returning the size -1 (to have enought space right and left) 
    return UIFont(name: fontName, size: tempMin - 1) 
} 

,我使用這種方式:

myLabel.font = optimisedfindAdaptiveFontWithName("Helvetica", label: myLabel, minSize: 10, maxSize: 38) 
    println("\(myLabel.font)") 
+0

得到這個工作真棒,除非使用小寫字母。有時他們只是在我的標籤框架之外:< – ClockWise 2016-01-04 11:57:06

+0

真的有效,但'var tempHeight:CGFloat'沒有必要。 – S1U 2016-04-05 09:07:17

+1

但是....我用它作爲'UIFont'擴展名,沒有改變,代碼像'aLabel.font.optimisedfindAdaptiveFontWithName(「.SFUIText-Regular」,label:fontLabel,minSize:10,maxSize:100)''。有什麼問題? – S1U 2016-04-05 09:32:08

35

我有同樣的問題,而且由於這個線程和喬爾的算法,我能解決它。 :-)

下面是我在Swift中的代碼。我在iOS 8 + Autolayout。

問題:

  1. 用戶輸入費用:

123 app

  • 當用戶點擊 '檢查' 按鈕,從底部出現一個菜單,將所有內容推到屏幕的頂部(shrinki NG的東西,包括標籤):
  • 123 app

    修復程序後:

    123 app

    這也正是設計師腦子裏想的是什麼? :)

    xScope app :)

    I子類別UILabel和覆蓋layoutSubviews。然後,每一個的UILabel得到它的大小改變時,字體大小被重新計算:

    // 
    // LabelWithAdaptiveTextHeight.swift 
    // 123 
    // 
    // Created by https://github.com/backslash-f on 12/19/14. 
    // 
    
    /* 
    Designed with single-line UILabels in mind, this subclass 'resizes' the label's text (it changes the label's font size) 
    everytime its size (frame) is changed. This 'fits' the text to the new height, avoiding undesired text cropping. 
    Kudos to this Stack Overflow thread: bit.ly/setFontSizeToFillUILabelHeight 
    */ 
    
    import Foundation 
    import UIKit 
    
    class LabelWithAdaptiveTextHeight: UILabel { 
    
        override func layoutSubviews() { 
         super.layoutSubviews() 
         font = fontToFitHeight() 
        } 
    
        // Returns an UIFont that fits the new label's height. 
        private func fontToFitHeight() -> UIFont { 
    
         var minFontSize: CGFloat = DISPLAY_FONT_MINIMUM // CGFloat 18 
         var maxFontSize: CGFloat = DISPLAY_FONT_BIG  // CGFloat 67 
         var fontSizeAverage: CGFloat = 0 
         var textAndLabelHeightDiff: CGFloat = 0 
    
         while (minFontSize <= maxFontSize) { 
    
          fontSizeAverage = minFontSize + (maxFontSize - minFontSize)/2 
    
          // Abort if text happens to be nil 
          guard text?.characters.count > 0 else { 
           break 
          } 
    
          if let labelText: NSString = text { 
           let labelHeight = frame.size.height 
    
           let testStringHeight = labelText.sizeWithAttributes(
            [NSFontAttributeName: font.fontWithSize(fontSizeAverage)] 
           ).height 
    
           textAndLabelHeightDiff = labelHeight - testStringHeight 
    
           if (fontSizeAverage == minFontSize || fontSizeAverage == maxFontSize) { 
            if (textAndLabelHeightDiff < 0) { 
             return font.fontWithSize(fontSizeAverage - 1) 
            } 
            return font.fontWithSize(fontSizeAverage) 
           } 
    
           if (textAndLabelHeightDiff < 0) { 
            maxFontSize = fontSizeAverage - 1 
    
           } else if (textAndLabelHeightDiff > 0) { 
            minFontSize = fontSizeAverage + 1 
    
           } else { 
            return font.fontWithSize(fontSizeAverage) 
           } 
          } 
         } 
         return font.fontWithSize(fontSizeAverage) 
        } 
    } 
    

    +0

    爲我工作。謝謝! – ObjectiveTC 2015-01-09 09:56:12

    +0

    它與我完美合作。投票100 100 – 2015-08-14 16:20:58

    +0

    太棒了!很高興我可以得到一些幫助。感謝您轉換爲Swift!動畫表現如何?考慮到這一點,我沒有寫出代碼。 – 2015-08-27 17:38:16

    4

    基於@ Conaaando最偉大的答案,我已經將它更新到版本包含IBDesignable參數,從而可以在整個Interface Builder中對其進行編輯:

    enter image description here

    ,代碼:

    // 
    // TIFFitToHeightLabel.swift 
    // 
    
    import Foundation 
    import UIKit 
    
    @IBDesignable class TIFFitToHeightLabel: UILabel { 
    
        @IBInspectable var minFontSize:CGFloat = 12 { 
         didSet { 
          font = fontToFitHeight() 
         } 
        } 
    
        @IBInspectable var maxFontSize:CGFloat = 30 { 
         didSet { 
          font = fontToFitHeight() 
         } 
        } 
    
        override func layoutSubviews() { 
         super.layoutSubviews() 
         font = fontToFitHeight() 
        } 
    
        // Returns an UIFont that fits the new label's height. 
        private func fontToFitHeight() -> UIFont { 
    
         var minFontSize: CGFloat = self.minFontSize 
         var maxFontSize: CGFloat = self.maxFontSize 
         var fontSizeAverage: CGFloat = 0 
         var textAndLabelHeightDiff: CGFloat = 0 
    
         while (minFontSize <= maxFontSize) { 
          fontSizeAverage = minFontSize + (maxFontSize - minFontSize)/2 
    
          if let labelText: NSString = text { 
           let labelHeight = frame.size.height 
    
           let testStringHeight = labelText.sizeWithAttributes(
            [NSFontAttributeName: font.fontWithSize(fontSizeAverage)] 
            ).height 
    
           textAndLabelHeightDiff = labelHeight - testStringHeight 
    
           if (fontSizeAverage == minFontSize || fontSizeAverage == maxFontSize) { 
            if (textAndLabelHeightDiff < 0) { 
             return font.fontWithSize(fontSizeAverage - 1) 
            } 
            return font.fontWithSize(fontSizeAverage) 
           } 
    
           if (textAndLabelHeightDiff < 0) { 
            maxFontSize = fontSizeAverage - 1 
    
           } else if (textAndLabelHeightDiff > 0) { 
            minFontSize = fontSizeAverage + 1 
    
           } else { 
            return font.fontWithSize(fontSizeAverage) 
           } 
          } 
         } 
         return font.fontWithSize(fontSizeAverage) 
        } 
    } 
    
    0

    對於調整比例較大/較小的設備UILabels:

    對我來說最有效的解決方案是將字體的點大小設置爲標籤的一些比高度+/-一個調整因子。假設使用自動佈局約束,將其垂直中心對齊到超視圖的底部,乘以比率。同樣在IB中,將標籤的寬度限制爲屏幕寬度的一部分。

    或者,您可以在標籤的高度/寬度,縱橫約束比鎖定,但是這可能會導致如果你沒有得到字體的點大小計算正確的剪裁。鎖定縱橫比的唯一原因是其他控件/視圖的位置是否與此標籤相關。不過,我強烈建議將這些控件/視圖相對於超級視圖的高度/寬度進行放置,以使它們不依賴於此標籤。

    我明白這是不完全的封裝解決方案,但它一直令我悲傷的最少。唯一的其他解決方案是使用while循環,但在我的情況下,我無法處理它們對每個佈局/刷新系統調用施加的延遲。所謂在viewWillAppear中

    3

    一號線的伎倆:

    testLabel.font = testLabel.font.fontWithSize(testLabel.frame.height * 2/3) 
    

    在故事板,我把所有標籤高度相對於視圖的整體高度,這使得字體大小與他們動態擴展。

    請注意,字體大小實際上是標籤高度的2/3。如果您使用的字體的尾部在線下方傾斜(如在y,g,q,p或j中),您需要將字體大小設置爲標籤高度的比率,以便這些尾部不會被切碎關閉。 2/3適用於Helvetica Neue,但根據您使用的字體嘗試其他比例。對於沒有尾部,數字或全部大寫字體的字體,1:1的比例就足夠了。

    +0

    這對我有效。儘管我選擇了接近1/2(而不是2/3)的東西。謝謝! – xta 2016-04-28 05:24:12

    6

    好消息,

    執行二進制搜索是完全沒有必要的!

    您只需要使用比率搜索來重複(幾次)。

     guess = guess * (desiredHeight/guessHeight) 
    

    下面是一個完整的總計IBDesignable解決方案。

    注意:在與設計師或印刷工合作時,您需要設置字體的跟蹤/拉伸。 (這是荒謬的蘋果不包括這個。)StyledLabel還包括跟蹤/拉伸。

    StyledLabel.swift

    它設置跟蹤,拉伸,並將其設置點的大小,以在所有設備上匹配視圖幀高度

    在故事板中:只是使UILabel的框架,你想要的文本的高度 - 故事的結尾!

    // the call fontToFitHeight FINDS THE POINT SIZE TO "FILL TO HEIGHT". 
    // Just use autolayout to make the frame THE ACTUAL HEIGHT 
    // you want the type ON ANY DEVICE 
    
    // ADDITIONALLY you can set: 
    // the tracking (that's the overall amount of space between all letters) 
    // and streching (actually squeeze or stretch the letters horizontally) 
    
    // Note: tracking and stretching IS SHOWN IN STORYBOARD LIVE 
    // WTT crazyrems http://stackoverflow.com/a/37300130/294884 
    
    import UIKit 
    
    @IBDesignable 
    class StyledLabel: UILabel 
        { 
        @IBInspectable var tracking:CGFloat = 0.8 
        // values between about 0.7 to 1.3. one means normal. 
    
        @IBInspectable var stretching:CGFloat = -0.1 
        // values between about -.5 to .5. zero means normal. 
    
        override func awakeFromNib() 
         { 
         tweak() 
         } 
    
        override func prepareForInterfaceBuilder() 
         { 
         tweak() 
         } 
    
        override func layoutSubviews() 
         { 
         super.layoutSubviews() 
         font = fontToFitHeight() 
         } 
    
        private func fontToFitHeight() -> UIFont 
         { 
    /* Apple have failed to include a basic thing needed in handling text: fitting the text to the height. Here's the simplest and fastest way to do that: 
    
         guess = guess * (desiredHeight/guessHeight) 
    
    That's really all there is to it. The rest of the code in this routine is safeguards. Further, the routine iterates a couple of times, which is harmless, to take care of any theoretical bizarre nonlinear sizing issues with strange typefaces. */ 
    
         guard text?.characters.count > 0 else { return font } 
         let desiredHeight:CGFloat = frame.size.height 
         guard desiredHeight>1 else { return font } 
         var guess:CGFloat 
         var guessHeight:CGFloat 
    
         print("searching for... ", desiredHeight) 
    
         guess = font.pointSize 
         if (guess>1&&guess<1000) { guess = 50 } 
    
         guessHeight = sizeIf(guess) 
    
         if (guessHeight==desiredHeight) 
          { 
          print("fluke, exact match within float math limits, up front") 
          return font.fontWithSize(guess) 
          } 
    
         var iterations:Int = 4 
    
    /* It is incredibly unlikely you would need more than four iterations, "two" would rarely be needed. You could imagine some very strange glyph handling where the relationship is non-linear (or something weird): That is the only theoretical reason you'd ever need more than one or two iterations. Note that when you watch the output of the iterations, you'll sometimes/often see same or identical values for the result: this is correct and expected in a float iteration. */ 
    
         while(iterations>0) 
          { 
          guess = guess * (desiredHeight/guessHeight) 
          guessHeight = sizeIf(guess) 
    
          if (guessHeight==desiredHeight) 
           { 
           print("unbelievable fluke, exact match within float math limits while iterating") 
           return font.fontWithSize(guess) 
           } 
    
          iterations -= 1 
          } 
    
         print("done. Shame Apple doesn't do this for us!") 
         return font.fontWithSize(guess) 
         } 
    
        private func sizeIf(pointSizeToTry:CGFloat)->(CGFloat) 
         { 
         let s:CGFloat = text!.sizeWithAttributes(
          [NSFontAttributeName: font.fontWithSize(pointSizeToTry)]) 
          .height 
    
         print("guessing .. ", pointSizeToTry, " .. " , s) 
         return s 
         } 
    
        private func tweak() 
         { 
         let ats = NSMutableAttributedString(string: self.text!) 
         let rg = NSRange(location: 0, length: self.text!.characters.count) 
    
         ats.addAttribute(
          NSKernAttributeName, value:CGFloat(tracking), range:rg) 
    
         ats.addAttribute(
          NSExpansionAttributeName, value:CGFloat(stretching), range:rg) 
    
         self.attributedText = ats 
         } 
        } 
    
    +0

    哇,這個作品完美 - 謝謝喬!對於這個代碼的Swift 3版本 - 你只需要製作Xcode建議的編輯。 – 2016-11-17 02:07:34

    0

    我的道歉,如果我在這裏漏掉了所有的文字。我跟着@Crazyrems suggestions自動縮水標籤的字體。這可以根據其他人觀察到的寬度來縮放字體。

    然後,我只是在Xcode的UILabel的字體部分中將'Lines'設置爲0。在代碼中,應該是numberOfLines。就這樣。

    感謝@Mikrasya,他在上面的評論中暗示了這個解決方案。

    在Xcode 7.3和iOS 9.3.2上測試。

    1

    有很多簡單的方式來做到這一點。只需計算屏幕上的每個像素的點數並將其乘以標籤的高度,即可獲得desiered字體大小。
    這裏是自定義的方法。選擇你想要的。

    TYPE 1。Hardoded單行版本:

    - (CGFloat) fontSizeFromHeight:(CGFloat)height 
    { 
        return ceilf(height * (10.0/[@"Tg" sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:10.0]}].height)); 
    } 
    

    TYPE 2.清潔版本:

    - (CGFloat)fontSizeFromHeight:(CGFloat)height 
    { 
        static CGFloat const testFontSize = 12.0; 
        static NSString * const testText = @"TestString"; 
        UIFont *testFont = [UIFont systemFontOfSize:testFontSize]; 
        CGFloat pixelHeight = [testText sizeWithAttributes:@{NSFontAttributeName:testFont}].height; 
        CGFloat pointPerPixel = testFontSize/pixelHeight; 
        CGFloat desiredFontSize = ceilf(height * pointPerPixel); 
        return desiredFontSize; 
    } 
    

    使用示例:

    myLabel.font = [UIFont systemFontOfSize:[self fontSizeFromHeight:myLabel.frame.size.height]]; 
    myLabel.font = [myLabel.font fontWithSize:[self fontSizeFromHeight:myLabel.frame.size.height]]; 
    
    0

    SWIFT變化:

    我設法用擴展名來做到這一點。工作正常,分鐘字體大小爲5. 我從高度減去10,所以我也留下了「邊距」,但是您可以刪除它或修改它。

    extension UILabel { 
    
    //Finds and sets a font size that matches the height of the frame. 
    //Use in case the font size is epic huge and you need to resize it. 
    func resizeToFitHeight(){ 
        var currentfontSize = font.pointSize 
        let minFontsize = CGFloat(5) 
        let constrainedSize = CGSizeMake(frame.width, CGFloat.max) 
    
        while (currentfontSize >= minFontsize){ 
         let newFont = font.fontWithSize(currentfontSize) 
         let attributedText: NSAttributedString = NSAttributedString(string: text!, attributes: [NSFontAttributeName: newFont]) 
         let rect: CGRect = attributedText.boundingRectWithSize(constrainedSize, options: .UsesLineFragmentOrigin, context: nil) 
         let size: CGSize = rect.size 
    
         if (size.height < frame.height - 10) { 
          font = newFont 
          break; 
         } 
    
         currentfontSize-- 
        } 
    
        //In case the text is too long, we still show something... ;) 
        if (currentfontSize == minFontsize){ 
         font = font.fontWithSize(currentfontSize) 
        } 
    } 
    

    }

    +0

    用法:youLabel.resizeToFitHeight()。而已。 – ely87 2016-08-17 11:21:53

    0

    擴展在@Joe吹的答案,這裏是一個Objective-C類UILabel+FitToHeight,讓您能夠輕鬆地導入和切換一個adjustsFontSizeToFitHeight就像你已經可以adjustsFontSizeToFitWidth

    的UILabel + FitToHeight.h

    #import <UIKit/UIKit.h> 
    
    @interface UILabel (FitToHeight) 
    
    @property (nonatomic, assign) BOOL adjustsFontSizeToFitHeight; 
    
    @end 
    

    的UILabel + FitToHeight.m

    #import "UILabel+FitToHeight.h" 
    
    #import <objc/runtime.h> 
    
    @implementation UILabel (FitToHeight) 
    
    -(BOOL)adjustsFontSizeToFitHeight { 
        NSNumber *number = objc_getAssociatedObject(self, @selector(adjustsFontSizeToFitHeight)); 
        return [number boolValue]; 
    } 
    
    -(void)setAdjustsFontSizeToFitHeight:(BOOL)adjustsFontSizeToFitHeight { 
        NSNumber *number = [NSNumber numberWithBool:adjustsFontSizeToFitHeight]; 
        objc_setAssociatedObject(self, @selector(adjustsFontSizeToFitHeight), number, OBJC_ASSOCIATION_ASSIGN); 
    } 
    
    -(UIFont *)fontToFitHeight { 
        float desiredHeight = [self frame].size.height; 
        float guess; 
        float guessHeight; 
    
        guess = [[self font] pointSize]; 
        guessHeight = [self sizeIf:guess]; 
        if(guessHeight == desiredHeight) { 
         return [[self font] fontWithSize:guess]; 
        } 
    
        int attempts = 4; 
        while(attempts > 0) { 
         guess = guess * (desiredHeight/guessHeight); 
         guessHeight = [self sizeIf:guess]; 
    
         if(guessHeight == desiredHeight) { 
          return [[self font] fontWithSize:guess]; 
         } 
    
         attempts--; 
        } 
    
        return [[self font] fontWithSize:guess]; 
    } 
    
    -(float)sizeIf:(float)sizeToTry { 
        CGSize size = [[self text] sizeWithAttributes:@{ NSFontAttributeName : [[self font] fontWithSize:sizeToTry] }]; 
        return size.height; 
    } 
    
    -(void)layoutSubviews { 
        [super layoutSubviews]; 
    
        if([self adjustsFontSizeToFitHeight]) { 
         [self setFont:[self fontToFitHeight]]; 
        } 
    } 
    

    導入,就像任何其他種類...

    #import "UILabel+FitToHeight.h"

    和使用方法如下...

    UILabel *titleLabel = [[UILabel alloc] init]; 
    [titleLabel setAdjustsFontSizeToFitHeight:YES]; 
    [titleLabel setAdjustsFontSizeToFitWidth:YES]; 
    

    值得一提的是這仍然作品與[titleLabel setAdjustsFontSizeToFitWidth:YES];所以使用兩個結合是完全可能的。

    11

    有一個更簡單的解決方案。只需添加下面的線條和神奇,標籤調整其字體大小以適合標籤的高度太:

    SWIFT 3:

    label.minimumScaleFactor = 0.1 //or whatever suits your need 
    label.adjustsFontSizeToFitWidth = true  
    label.lineBreakMode = .byClipping 
    label.numberOfLines = 0 
    
    +2

    這是唯一正確的答案。 – Manuel 2017-08-02 00:44:43

    0

    原諒我,如果我錯了,但這裏所說的一切都是不必要。使用yourLabel的新fontSize更改後再次設置字體。

    您還可以檢查這些值(yourLabel.height和fontSize)之間的條件比較以防止不必要的更新。

    所有你需要做的是:

    [yourLabel setFont:[UIFont fontWithName:@"*your fontname*" size:yourLabel.frame.size.height]]; 
    
    0

    結合以@DGund和@Kashif答案,這裏有一個簡單的解決方案IB:

    enter image description here

    這由高度低至適合文本你在Autoshrink參數中指定。

    相關問題