是否可以动态更改UIAlertView的消息?

时间:2013-07-19 14:40:31

标签: ios uitextfield uialertview

在我的应用中,用户可以创建新文件。我使用样式为UIAlertViewStylePlainTextInput的UIAlertView来提示用户输入新文件的名称。当然,我想确保在文本字段中输入的文件名不存在。

因此,每当用户更改警报视图的文本字段中的文本时,我想测试是否存在具有该名称的文件,如果存在,则通过设置警报视图的消息来通知用户:

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

在所有其他情况下,当不存在具有该名称的文件时,我根本不想显示消息。我尝试了几件事,但似乎实现这一目标的唯一方法是在后一种情况下使用空格字符:

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

这里的缺点是警报视图在大多数情况下会显示一个空行(当没有这样的名称时),我想避免这种情况。我怎样才能做到这一点? 或者是否有另一种更好的方式来通知用户?

2 个答案:

答案 0 :(得分:1)

创建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";
}

我们正在调用一个获取字符串的方法,在该方法中我们可以创建条件语句来查看我们想要使用的字符串。

答案 1 :(得分:1)

尝试通过调用[self performSelectorInBackground:withObject:]在新线程中运行您的任务,并通过调用[self performSelectorOnMainThread:withObject:waitUntilDone:]来更新UIAlertView文本。我刚成功了。

这个主题也可能很有用,介绍计算和调整alertView框架与动画的平滑度 Updating UIAlertView Message dynamically and newline character issue

相关问题