开发者

How to make UITextView "Done" button resignFirstResponder?

I am trying to make my editable UITextView resign the keyboard (resignFirstResponder) when the user taps "Done." Using a UITextField, I have been able to do this with the following code:

- (IBAction)doneEditing:(id)sender {
    [sender resignFirstResponder];
}

... a开发者_如何学编程nd then to attach it to the relevant UITextField in Interface Builder to the action "Did End on Exit."

However, with a UITextView, I can't seem to access the "Did End on Exit" action. Any suggestions on how to make this happen?


The accepted answer didn't work for me. Instead, the following delegate method should be invoked like this:

- (BOOL) textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if([text isEqualToString:@"\n"]){
        [textView resignFirstResponder];
        return NO;
    }else{
        return YES;
    }
}

Paste that into the class that you assign to be the UITextView delegate and it'll work.


new Answer

On your View, you'd have a UIBarButton ("Done") that is connected to the IBAction below:

- (IBAction)doneEditing:(id)sender {
    [textView resignFirstResponder];
}

Where textView is your textView outlet defined in your .h file and connected in Storyboard or .xib file. Like this:

@property (retain, nonatomic) IBOutlet UITextView *textView;

old Answer

Check the following:

  1. Is UITextViewDelegate specified in .h
  2. Implement delegate method for uitextview: textViewShouldEndEditing, return YES
  3. make sure your .m (controller) is the delegate for uitextview in IB
  4. resignFirstResponder should now work.


You can implement UITextViewDelegate and wait for "\n", in Swift 4 :

    myTextView.delegate = self

// ...

extension MyViewController : UITextViewDelegate {

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

        return true
    }
}


To have the done button dismiss the keyboard and resignFirstResponder you have to implement a delegate method.

  1. In your .h implement the UITextFieldDelegate

    @interface YourViewController : UIViewController <UITextFieldDelegate>
    
  2. Then implement the textFieldShouldReturn in your .m

    -(BOOL) textFieldShouldReturn:(UITextField *)textField
    {
    [textField resignFirstResponder];
    return YES;
    }
    
  3. Don't forget to link the delegate of UITextField to the file's Owner (very important)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜