Skip to content

Instantly share code, notes, and snippets.

@cactis
Forked from nRewik/UILabel+FontSize.Swift
Created February 26, 2016 06:48
Show Gist options
  • Save cactis/a23d954e789f62a8b29d to your computer and use it in GitHub Desktop.
Save cactis/a23d954e789f62a8b29d to your computer and use it in GitHub Desktop.

Revisions

  1. @nRewik nRewik revised this gist Aug 8, 2015. No changes.
  2. @nRewik nRewik created this gist Aug 8, 2015.
    49 changes: 49 additions & 0 deletions UILabel+FontSize.Swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    //
    // UILabel+FontSize.Swift
    //
    // Created by Nutchaphon Rewik on 7/11/15.
    // Copyright (c) 2015 Nutchaphon Rewik. All rights reserved.
    //

    import UIKit

    extension UILabel{

    func adjustFontSizeToFitRect(rect : CGRect){

    if text == nil{
    return
    }

    frame = rect

    var maxFontSize: CGFloat = 100.0
    let minFontSize: CGFloat = 5.0

    var q = Int(maxFontSize)
    var p = Int(minFontSize)

    let constraintSize = CGSize(width: rect.width, height: CGFloat.max)

    while(p <= q){
    let currentSize = (p + q) / 2
    font = font.fontWithSize( CGFloat(currentSize) )
    let text = NSAttributedString(string: self.text!, attributes: [NSFontAttributeName:font])
    let textRect = text.boundingRectWithSize(constraintSize, options: .UsesLineFragmentOrigin, context: nil)

    let labelSize = textRect.size

    if labelSize.height < frame.height &&
    labelSize.height >= frame.height-10 &&
    labelSize.width < frame.width &&
    labelSize.width >= frame.width-10 {
    break
    }else if labelSize.height > frame.height || labelSize.width > frame.width{
    q = currentSize - 1
    }else{
    p = currentSize + 1
    }
    }

    }
    }