UiAlertController在没有用户输入的情况下自动消失

时间:2017-06-12 17:40:14

标签: objective-c uialertcontroller

当用户未在特定字段中输入文本时,我试图提示警告UIAlertAction。当字段缺少文本并且用户按下发送时,警报会暂时显示,然后解除。

#pragma mark - Actions
- (IBAction)sendPressed:(id)sender
{
    if (_titleLabel.text.length == 0)
 {
    self.alert = [UIAlertController alertControllerWithTitle:@"Sorry"
                                                                   message:@"Please enter a title, it is required"
                                                            preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                          handler:^(UIAlertAction *action) {
                                                              [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [self.alert addAction:defaultAction];
    [self presentViewController:self.alert animated:YES completion:nil];

}
else
{
}
if (_delegate && [_delegate respondsToSelector:@selector(reportControllerDidPressSend:)]) {
    [_delegate reportControllerDidPressSend:self];
}

1 个答案:

答案 0 :(得分:1)

您是否知道,您有一个空的else分支和一个独立的第二个if语句?我很确定,你想要一个else if - 状态意味着

此外,如果代表是nil则不需要进行测试。

#pragma mark - Actions
- (IBAction)sendPressed:(id)sender
{
    if (_titleLabel.text.length == 0) {
       self.alert = [UIAlertController alertControllerWithTitle:@"Sorry"
                                                                   message:@"Please enter a title, it is required"
                                                            preferredStyle:UIAlertControllerStyleAlert];

       UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                          handler:^(UIAlertAction *action) {
                                                              [self dismissViewControllerAnimated:YES completion:nil];
        }];
        [self.alert addAction:defaultAction];
        [self presentViewController:self.alert animated:YES completion:nil];

    } else if([_delegate respondsToSelector:@selector(reportControllerDidPressSend:)])) {
        [_delegate reportControllerDidPressSend:self];
    }
}