Groppe Groppe - 1 year ago 93
iOS Question

Updating UIAlertView Message dynamically and newline character issue

I need to display multiple lines of text in the message of my UIAlertView. I have tried adding a '\n', but it has no effect. It still displays: "This is an examp....".

HOWEVER, if I turn my iPhone to landscape mode it displays the message as I intend it to. And then if I switch BACK to portrait mode it displays correctly there as well.

Update: After further consideration, I suspect it has something to do with the fact that I am updating the current message with a new (and much longer) string. I have already called "show" on the alert view, and am trying to update the message. Perhaps something needs to be redrawn? Like i said before, it displays correctly if I change orientations (doesn't matter which orientation I start in, i still have the same problem). i have already tried "setNeedsDisplay" and "setNeedsLayout".

Answer Source

Although I believe updating the alert view's text while it's being displayed is wrong, the only way I see to change it is this way

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"test" message:@"this is a message\nthis is a new line text" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:@"test button",nil];  
[alert show];

//set the new message
NSString *newMessage = [NSString stringWithString:@"Test\nWith a new message with\ncustom new line string\n and a lot\n of new lines\n Yep"];
[alert setMessage:newMessage];

//get the original alert Frame
CGRect alertFrame = alert.frame;
//get the alert view Label
UILabel *alertLabel = [alert.subviews objectAtIndex:2];
//and get the original frame position
CGRect alertLabelFrame = alertLabel.frame;

//see how much space we are needing for the new message and adjust
int heightChange = [newMessage sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(alertLabelFrame.size.width, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap].height - alertLabelFrame.size.height;

alertFrame.size.height += heightChange;
//adjust the Label height to the new height
alertLabelFrame.size.height += heightChange;

//adjust the frame and elements with an animation for smoothness
[UIView animateWithDuration:0.15 delay:0.4 options:(UIViewAnimationCurveEaseIn) animations:^{
    [alert setFrame:alertFrame];           
    alertLabel.frame = alertLabelFrame;
    //move any buttons
    for (UIView *subView in alert.subviews) {
        if ([subView isKindOfClass:[UIButton class]]) {
            //this is a button move it
            UIButton *button = (UIButton*)subView;
            CGRect alertButtonFrame = button.frame;
            //adjust button Y position to the new height
            alertButtonFrame.origin.y += heightChange-5;
            button.frame = alertButtonFrame;
} completion:nil];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download