Wednesday, September 14, 2011

Customize your UIKeyboard with toolbar

So you are looking to put a toolbar on top of your keyboard with bunch of button on it as shown in the screenshot below.

The toolbar view will be attached with as inputAccessoryView of the textfield or textview.




















Important code snippets can be seen here. You can download the complete code below with the link.


//One main thing you need to do is add the notification for showing and hiding keyboard


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];


//Next thing is to add the toolbarview as accessoryview. Here I am loading it off the nib file.


[[NSBundle mainBundle] loadNibNamed:@"AccessoryView" owner:self options:nil];
textView.inputAccessoryView = accessoryView;  //Make sure you have connection as in sample code.


//Notification Handlers

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

    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

   
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    
    CGFloat keyboardTop = keyboardRect.origin.y;
    CGRect newTextViewFrame = self.view.bounds;
    newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y;
    

    NSValue *animationDurationValue = [userInfo     objectForKey:UIKeyboardAnimationDurationUserInfoKey];    
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    
    textView.frame = newTextViewFrame;

    [UIView commitAnimations];
}


- (void)keyboardWillHide:(NSNotification *)notification {
    
    NSDictionary* userInfo = [notification userInfo];

    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    
    textView.frame = self.view.bounds;
    
    [UIView commitAnimations];
}




You can download the code HERE

No comments:

Post a Comment