Saturday, March 3, 2012

Dismiss the keyboard when pressing the "Return" key

1. Except to use the IB to change the "Return" to be "Done" for the keyboard, it can be done in code as below.


 [myTextField setReturnKeyType:UIReturnKeyDone];

2. Dimiss the keyboard after pressing "Return" button for textfield, link this method to the "Did End on Exit" Event in the textfield. Remember to add UITextViewDelegate in .h file.

// dismisses the keyboard when a user selects the return key
- (IBAction)textFieldShouldReturn:(id)sender
{
    [sender resignFirstResponder];

    
}

3. If you want to dismiss the keyboard in the myTextView, please find the below code.

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if([text isEqualToString:@"\n"]) {
        [myTextView resignFirstResponder];
        return NO;
    }
    
    return YES;
}
Besides it, you need to add UITextViewDelegate at .h file, also link delegate to file owner in reference outlet.

No comments:

Post a Comment