UILabel auto resize on basis of text to be shown
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 find a text size with :
CGSize textSize = [[myObject getALongText] sizeWithFont:[UIFont boldSystemFontOfSize:15] constrainedToSize:CGSizeMake(maxWidth, 2000) lineBreakMode:UILineBreakModeWordWrap];
then you can create your UILabel
like that :
UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake(0,0,textSize.width, textSize.height];[lbl setNumberOfLines:0];[lbl setLineBreakMode:UILineBreakModeWordWrap];[lbl setText:[myObject getALongText]];
In Swift:
testLabel = UILabel(frame: CGRectMake(6, 3, 262, 20))testLabel.text = testtestLabel.numberOfLines = 0testLabel.sizeToFit()
In Objective C
UILabel *testLabel = [[UILabel alloc] initWithFrame: CGRectMake(6, 3, 262, 20)]];testLabel.text = test;testLabel.numberOfLines = 0;[testLabel sizeToFit];