I'm trying to display some random text into a UILabel
and of course I have nothing but its width. Is there a way to set my UILabel
's height and/or number of lines depending by the text contained in it?
Thanks ;)
myUILabel.numberOfLines = 0;
myUILabel.text = @"Pass random text here";
[myUILabel sizeToFit];
For Swift 4.0
func getStringHeight(mytext: String, fontSize: CGFloat, width: CGFloat)->CGFloat {
let font = UIFont.systemFont(ofSize: fontSize)
let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping;
let attributes = [NSAttributedStringKey.font:font,
NSAttributedStringKey.paragraphStyle:paragraphStyle.copy()]
let text = mytext as NSString
let rect = text.boundingRect(with: size,
options:.usesLineFragmentOrigin,
attributes: attributes,
context:nil)
return rect.size.height
}
Or (if you need the height of the label for a specific width and font size, you could calculate it with this):
func getStringHeight(mytext: String, fontSize: CGFloat, width: CGFloat)->CGFloat {
let font = UIFont.systemFontOfSize(fontSize)
let size = CGSizeMake(width,CGFloat.max)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .ByWordWrapping;
let attributes = [NSFontAttributeName:font,
NSParagraphStyleAttributeName:paragraphStyle.copy()]
let text = mytext as NSString
let rect = text.boundingRectWithSize(size, options:.UsesLineFragmentOrigin, attributes: attributes, context:nil)
return rect.size.height
}
You need this for Swift or for Objective C?
You can use NSString UIKIT Addition
method
- (CGSize)sizeWithFont:(UIFont *)font
constrainedToSize:(CGSize)size
lineBreakMode:(NSLineBreakMode)lineBreakMode
to calculate the hight. something like.
CGSize yourLabelSize = [@"Your very long text" sizeWithFont:yourFont constrainedToSize:CGSizeMake(desiredMaximumWidth, 2000) lineBreakMode:NSLineBreakByWordWrapping];
its really important to understand the constrainedToSize
parameter. You have to pass a CGSize
with desired maximum
width and maximum possible height
. Use the same UIFont
with your label. Dont forget to set the
[yourLabel setNumberOfLines:0];
But the method is already deprecated in iOS 7
therefore you have to use
- (CGRect)boundingRectWithSize:(CGSize)size
options:(NSStringDrawingOptions)options
attributes:(NSDictionary *)attributes
context:(NSStringDrawingContext *)context
yourLabelSize.height
will give you the height
hope it will help you...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With