在IB的库中,介绍告诉我们,当按下返回键时,UITextView的键盘将消失。但实际上返回键只能作为'\n'

我可以添加一个按钮,并使用[txtView resignFirstResponder]隐藏键盘。

但是有没有办法为键盘中的返回键添加动作,这样我就不需要添加UIButton了?


当前回答

你也可以隐藏键盘时,触摸在视图屏幕:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
     UITouch * touch = [touches anyObject];
     if(touch.phase == UITouchPhaseBegan) {
        [txtDetail resignFirstResponder];
      }
 }

其他回答

我想我应该把这个片段放在这里:

确保声明了对UITextViewDelegate协议的支持。

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }

    return YES;
}

Swift 4.0更新:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == "\n" {
        textView.resignFirstResponder()
        return false
    }
    return true
}

在viewDidLoad中添加一个观察者

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(textViewKeyPressed:) name: UITextViewTextDidChangeNotification object: nil];

然后使用选择器检查"\n"

-(void) textViewKeyPressed: (NSNotification*) notification {

  if ([[[notification object] text] hasSuffix:@"\n"])
  {
    [[notification object] resignFirstResponder];
  }
}

它确实使用“\n”,而不是专门检查返回键,但我认为这是可以的。

更新

参见下面ribto的答案,它使用[NSCharacterSet newlineCharacterSet]来代替\n

UITextView没有任何在用户点击返回键时被调用的方法。如果您希望用户只能添加一行文本,请使用UITextField。按回车键并隐藏UITextView的键盘不符合接口准则。

即使这样,如果你想这样做,实现textView:shouldChangeTextInRange:replacementText:方法的UITextViewDelegate,并在检查替换文本是否\n,隐藏键盘。

也许还有别的办法,但我不知道有什么办法。

在使用uitextview时还有另一个解决方案, 你可以添加工具栏作为InputAccessoryView在“textViewShouldBeginEditing”,并从这个工具栏的完成按钮,你可以解雇键盘,这是如下代码:

在viewDidLoad

toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)]; //toolbar is uitoolbar object
toolBar.barStyle = UIBarStyleBlackOpaque;
UIBarButtonItem *btnDone = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(btnClickedDone:)];
[toolBar setItems:[NSArray arrayWithObject:btnDone]];

在textviewdelegate方法

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
     [textView setInputAccessoryView:toolBar];
     return YES;
}

在操作按钮完成,这是在工具栏如下:

-(IBAction)btnClickedDone:(id)sender
{
    [self.view endEditing:YES];
}

好的。每个人都用技巧给出了答案,但我认为实现这一点的正确方法是

将以下操作连接到接口生成器中的“Did End On Exit”事件。 (右键单击TextField并从“Did end on exit”中cntrl-drag到以下方法。

-(IBAction)hideTheKeyboard:(id)sender
{
    [self.view endEditing:TRUE];
}