簡體   English   中英

ios鍵盤不能針對UIAlertController中的UITextField自動顯示

[英]ios Keyboard must not show up automatically for a UITextField in UIAlertController

我試圖用文本字段顯示UIAlertController。 當它啟動時,keyfoard會自動顯示為文本字段,從而自動獲得焦點。 如何在沒有鍵盤的情況下使用文本字段顯示警報(僅當用戶單擊文本字段時才顯示警報)。

這是我的代碼

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Collect Input"    message:@"input message"
    preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"Submit" style:UIAlertActionStyleDefault
    handler:^(UIAlertAction * action) {
        //use alert.textFields[0].text
    }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"Cancel" handler:^(UIAlertAction * action) {
    //cancel action
    }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
         // A block for configuring the text field prior to displaying the alert
         //[textField resignFirstResponder];

    }];
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:NO completion:nil];

有一些解決方案。

  1. 您可以在addTextFieldWithConfigurationHandler回調中獲取對文本字段的addTextFieldWithConfigurationHandler ,並將其存儲在本地變量中。 然后,在presentViewController的完成處理程序中,您可以在文本字段上調用resignFirstResponder 但是此解決方案遠非理想之選,因為鍵盤會出現然后立即被關閉。

  2. 更好的方法是設置文本字段的delegate並實現shouldBeginEditing委托方法。 添加實例變量以充當標志。 第一次shouldBeginEditing調用shouldBeginEditing ,而不是未設置標志,對其進行設置,然后返回NO 然后,每次之后,檢查標志並返回YES

這是選項2的實現:

指示您的類符合.m文件中的UITextFieldDelegate協議:

@interface YourClassHere () <UITextFieldDelegate>
@end

為該標志添加一個實例變量:

BOOL showKeyboard = NO;

更新您的警報設置代碼以設置文本字段的委托:

[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
    textField.delegate = self;
}];

實現文本字段委托方法:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (showKeyboard) {
        return YES;
    } else {
        showKeyboard = YES;
        return NO;
    }
}

這樣可以防止鍵盤的初始顯示,但之后可以隨時顯示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM