I have been trying hard to adjust label for my UIAlertView, and I am not successful. I want to make it resize correctly as per the string length. I read that there is not much one can do except to subclass it, but when I was about to do it, I found a trick to play with it. (code below)
I could successfully resize it, format fonts etc for small strings. I can fit some of my strings (<1000 chars) nicely, but larger strings (>1000 chars) make it ugly:
The whole thing looks completely messed up.
Here is how I sneaked into UIAlertView appearance code:
-(void)willPresentAlertView:(UIAlertView *)alertView
{
UILabel *body = [alertView valueForKey:@"_bodyTextLabel"];
body.lineBreakMode = UILineBreakModeWordWrap;
// body.adjustsFontSizeToFitWidth = YES;
CGRect alFrame = body.frame;
CGFloat pointSize;
UIFont * font = [UIFont fontWithName:@"Verdana" size:10];
CGSize labelSize = [body.text sizeWithFont:font minFontSize:8 actualFontSize:&pointSize forWidth:alFrame.size.width lineBreakMode:UILineBreakModeWordWrap];
NSLog (@"%f", labelSize.height);
UIFont *actualFont = [UIFont fontWithName:@"Verdana" size:10];
CGSize sizeWithCorrectHeight = [body.text sizeWithFont:actualFont];
alFrame.size.height = sizeWithCorrectHeight.height*10;
NSLog (@"%f - %f", alFrame.size.height, alFrame.size.width);
body.numberOfLines = 8;
body.frame = alFrame;
body.font = actualFont;
}
Note that commented lines are things which I have tried with thousand twists. And uncommented ones too produce the same effect. Smaller text adjust just as I have coded here. I just need a solution that can make my label display all text, irrespective of string length - I know there is plenty of room on it still but it just doesn't resize for larger strings that's it.
Here is a hack that I have used successfully in many shipping apps.
sizeWithFont
to figure out how much space you need (from the message text).@"\n"
. UILabel
as a subview of the alert view with your text. If you need really long texts, you could try inserting a UITextView
, which theoretically can be scrolled. (Please tell me if it works if you try it.) However, I would strongly advise not to use this design and construct a proper view controller instead.
[alertView addSubview:label];