Mischa
Mischa

Reputation: 17231

Is it possible to dynamically change the message of a UIAlertView?

In my app a user can create a new file. I use a UIAlertView with style UIAlertViewStylePlainTextInput to prompt the user to enter a name for the new file. Of course, I want to make sure that the file name entered in the text field does not already exist.

So whenever the user changes the text in the alert view's text field I want to test if a file with that name exists and if so notify the user by setting the alert view's message:

alertView.message = @"File exists! Please enter a different name.";

In all other cases, when a file with that name does not exist, I do not want to show a message at all. I have tried several things but it seems like the only way to achieve this goal is to use a space character in the latter case:

if (fileExists) {
    alertView.message = @"File exists! Please enter a different name.";
} else {
    alertView.message = @" ";
}

The disadvantage here is that the alert view will show an empty line in most cases (when no such with that name exists) and I would like to avoid that. How can I do that? Or is there another maybe better way to notify the user?

Upvotes: 1

Views: 2087

Answers (2)

AdrianHou
AdrianHou

Reputation: 211

Try to run your task in a new thread by calling [self performSelectorInBackground:withObject:] and update UIAlertView text by calling [self performSelectorOnMainThread:withObject:waitUntilDone:]. I just succeeded.

This topic may also be useful, introducing calculate and adjust alertView frame with an animation for smoothness Updating UIAlertView Message dynamically and newline character issue

Upvotes: 1

Dummy Code
Dummy Code

Reputation: 1898

Create alertView

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:[self getAlert] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];

getAlert

- (NSString *)getAlert {
    if(true) {
        return @"String 1";
    } else {
        return @"String 2";
    }
    return @"null";
}

We are calling a method to get a string and in that method we can create our conditional statements to see what string we want to use.

Upvotes: 1

Related Questions