【问题标题】:Show a UIAlertController having a UITextField without dismissing the keyboard在不关闭键盘的情况下显示具有 UITextField 的 UIAlertController
【发布时间】:2015-10-20 05:12:40
【问题描述】:

我尝试了一个非常简单的例子。我在视图控制器的视图中添加了一个文本视图和一个按钮。当按下按钮时,它会显示一个带有文本字段的警报视图。

我的问题如下:

假设我正在文本视图上进行编辑并按下按钮以显示警报视图。键盘将首先关闭(文本视图退出第一响应者)然后再次出现(文本字段成为第一响应者)。这真的很烦人。我想看看我能不能做点什么,这样当我从文本视图切换到文本字段时,键盘就不会关闭并停留。谢谢大家。

下面是这个简单例子的一些代码:

- (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];
}

【问题讨论】:

  • 我不认为你可以这样做,除非你使用自定义键盘

标签: ios keyboard textview uitextview uialertcontroller


【解决方案1】:

基于这个答案:Keyboard hide and show again...

我认为您可以在 .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

【讨论】:

  • 它不起作用。当显示警报视图时,键盘会向下移动一点(试图关闭),然后快速向上移动回到原来的位置。
  • 这是因为呈现UIAlertController时的动画!您可以使用[self presentViewController:ac animated:NO completion:nil]; 禁用它,但我认为您的屏幕上会出现一个快速的阴影。重要的是要了解 UIAlertController 是位于顶部的视图控制器。所以,也许用 UITextField 编写一个看起来像 UIAlertView 的自定义 UIView 更容易?!另外我不知道你想做什么,但也许是最好的 UX/UI 解决方案......
【解决方案2】:

实现UITextFieldDelegate Protocol 并将此方法添加到您的控制器:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
 {
      return NO;
 }

这应该可以防止键盘被关闭。

【讨论】:

  • textFieldShouldReturn 未被调用。调用其他委托方法,例如 textFieldDidBeginEditing。所以,我相信委托不是零。
猜你喜欢
  • 1970-01-01
  • 2018-03-03
  • 1970-01-01
  • 2016-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
相关资源
最近更新 更多