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

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

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


当前回答

用另一种方法解决了这个问题。

Create a button that will be placed in the background From the Attribute Inspector, change the button type to custom, and the makes the button transparent. Expand the button to cover the whole view, and make sure the button is behind all the other object. Easy way to do this is to drag the button to the top of list view in the View Control drag the button to the viewController.h file and create an action (Sent Event: Touch Up Inside) like : (IBAction)ExitKeyboard:(id)sender; In ViewController.m should look like : (IBAction)ExitKeyboard:(id)sender { [self.view endEditing:TRUE]; } Run app, and when you click away from the TextView, the keyboard disappears

其他回答

不要忘记为textView设置委托-否则resignfirstresponder将无法工作。

迅速回答:

override func viewDidLoad() {
    super.viewDidLoad()
    let tapGestureReconizer = UITapGestureRecognizer(target: self, action: "tap:")
    view.addGestureRecognizer(tapGestureReconizer)
}

func tap(sender: UITapGestureRecognizer) {
    view.endEditing(true)
}

我使用这段代码来更改响应器。

 - (BOOL)textView:(UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
    {
        if ([text isEqualToString:@"\n"]) {
            //[textView resignFirstResponder];
            //return YES;
            NSInteger nextTag = textView.tag + 1;
            // Try to find next responder
            UIResponder* nextResponder = [self.view viewWithTag:nextTag];
            if (nextResponder) {
                // Found next responder, so set it.
                [nextResponder becomeFirstResponder];
            } else {
                // Not found, so remove keyboard.
                [textView resignFirstResponder];
            }
            return NO; 


            return NO;
        }
        return YES;

    }
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range  replacementText:(NSString *)text
{
    if (range.length==0) {
        if ([text isEqualToString:@"\n"]) {
            [txtView resignFirstResponder];
            if(textView.returnKeyType== UIReturnKeyGo){

                [self PreviewLatter];
                return NO;
            }
            return NO;
        }
    }   return YES;
}

在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