Thursday, May 5, 2011

How to Dismiss the Keyboard when using a UITextView

The short answer is to send the UITextViewController the “resignFirstResponder” message … the trick however is when to send the message. In my case, and I assume it would be the same for others, is to listen for any changes to the text in the UITextView and if the carridge return character ‘\n’ is detected then send the “resignFirstResponder” message to the UITextView.
Step 1. The first step is to make sure that you declare support for the UITextViewDelegate protocol. This is done in your header file, as example here is the header called EditorController.h:
@interface EditorController : UIViewController  {
  UITextView *messageTextView;
}
 
@property (nonatomic, retain) UITextView *messageTextView;
 
@end
Step 2. Next you will need to register the controller as the UITextView’s delegate. Continuing from the example above, here is how I have initialize the UITextView with EditorController as the delegate …
- (id) init {
    if (self = [super init]) {
        // define the area and location for the UITextView
        CGRect tfFrame = CGRectMake(10, 10, 300, 100);
        messageTextView = [[UITextView alloc] initWithFrame:tfFrame];
        // make sure that it is editable
        messageTextView.editable = YES;
 
        // add the controller as the delegate
        messageTextView.delegate = self;
    }
Step 3. And now the final piece of the puzzle is to take action in response to the “shouldCahngeTextInRange” message as follows:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
  replacementText:(NSString *)text
{
    // Any new character added is passed in as the "text" parameter
    if ([text isEqualToString:@"\n"]) {
        // Be sure to test for equality using the "isEqualToString" message
        [textView resignFirstResponder];
 
        // Return FALSE so that the final '\n' character doesn't get added
        return FALSE;
    }
    // For any other character return TRUE so that the text gets added to the view
    return TRUE;
}

No comments:

Post a Comment