Last active
April 22, 2024 20:49
-
-
Save nRewik/dfc11fda310882a6516c to your computer and use it in GitHub Desktop.
iOS-Swift adjust font size to fit in rect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 | |
} | |
} | |
} | |
} |
Aug 8 2015... damn
I was at home, playing Battlefield 3 on Noshahr Canals, running around with knife and X-BOW
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It doesn't work as I expected, just takes max fontSize. =(