[英]Show a UIAlertController having a UITextField without dismissing the keyboard
我嘗試一個非常簡單的例子。 我在視圖控制器的視圖中添加了一個文本視圖和一個按鈕。 按下按鈕后,將顯示帶有文本字段的警報視圖。
我的問題如下:
假設我正在文本視圖上進行編輯,然后按按鈕以顯示警報視圖。 鍵盤將首先關閉(文本視圖退出第一響應者),然后再次出現(文本字段成為第一響應者)。 真煩人。 我想看看是否可以做些什么,這樣當我從文本視圖切換到文本字段時,鍵盤不會關閉並保持住。 謝謝你們。
以下是此簡單示例的一些代碼:
- (void)viewDidLoad {
[super viewDidLoad];
// Text view
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 100, 300, 300)];
textView.backgroundColor = [UIColor greenColor];
[self.view addSubview:textView];
// Button
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(100,500, 200, 100);
[button setTitle:@"Show alert view" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
-(void)buttonPressed {
UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"Title" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {}];
[ac addAction:cancelAction];
[ac addTextFieldWithConfigurationHandler:^(UITextField *textField) {}];
[self presentViewController:ac animated:YES completion:nil];
}
基於此答案: 鍵盤再次隱藏並顯示...
我認為您可以將這些行添加到.m文件的末尾,這樣就可以完成工作!
// UI AlertController Category
@interface UIAlertController (NonFirstResponder)
@end
@implementation UIAlertController (NonFirstResponder)
- (BOOL)canBecomeFirstResponder
{
return NO;
}
@end
// UIAlertAction Category
@interface UIAlertAction (NonFirstResponder)
@end
@implementation UIAlertAction (NonFirstResponder)
- (BOOL)canBecomeFirstResponder
{
return NO;
}
@end
實現UITextFieldDelegate Protocol
,並將此方法添加到您的控制器中:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
return NO;
}
這樣可以防止解雇鍵盤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.