I\'m working on an application, in which I\'m required to autoresize the text area on basis of text to be displayed.
Firstly, I\'m not sure for this either I should use
The sizeToFit
method worked just great.
I did following.
UILabel *testLabel =[[UILabel alloc] initWithFrame:CGRectMake(6,3, 262,20 )]; // RectMake(xPos,yPos,Max Width I want, is just a container value);
NSString * test=@"this is test this is test inthis is test ininthis is test inthis is test inthis is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...";
testLabel.text = test;
testLabel.numberOfLines = 0; //will wrap text in new line
[testLabel sizeToFit];
[self.view addSubview:testLabel];
You can change the size of label based on length of the string by, using this function
func ChangeSizeOfLabel(text:String) -> CGSize{
let font = UIFont(name: "HelveticaNeue", size: 12)!
let textAttributes = [NSFontAttributeName: font]
let size = text.boundingRectWithSize(CGSizeMake(310, 999), options: .UsesLineFragmentOrigin, attributes: textAttributes, context: nil)
let adjustSize = CGSizeMake(size.width, size.height)
return adjustSize
}
and use it like this :
let
showLabel.frame = CGRectMake(x, y, width , self.ChangeSizeOfLabel("Hello , Height is changing dynamically.....").height)
Because you're going to use this solution countless times in your app, do the following:
1) Create a directory called extensions
and add a new file inside called UILabel.swift
with the following code:
import UIKit
extension UILabel {
func resizeToText() {
self.numberOfLines = 0
self.sizeToFit()
}
}
2) In your app code, define the label width you want and just call resizeToText()
:
label.frame.size.width = labelWidth
label.resizeToText()
This will maintain width while increasing the height automatically.
try bellow code, it works for multiline
self.labelText.text = string;
self.labelText.lineBreakMode = NSLineBreakByWordWrapping;
self.labelText.numberOfLines = 0;