About Me

My photo
Dhaka, Bangladesh
I am B.S.C Engineer,CSE,SUST and Ex-Cadet of Mirzapur Cadet College.
Showing posts with label move a view. Show all posts
Showing posts with label move a view. Show all posts

Tuesday, May 29, 2012

How to move up the UIView while writing in UITextField


Inside .h File of your ViewController



Declare UIText field delegate(
) in .h file




- (void)setViewMovedUp:(BOOL)movedUp;



Inside .m file of your ViewController

-(void)textFieldDidBeginEditing:(UITextField *)sender
{
NSLog(@"Inside textFieldDidBeginEditing");
    if ([sender isEqual:leftTextField] || [sender isEqual:rightTextField])
    {
NSLog(@"Inside textFieldDidBeginEditing (INSIDE IF)");
        //move the main view, so that the keyboard does not hide it.
        if  (self.view.frame.origin.y >= 0)
        {
NSLog(@"Inside textFieldDidBeginEditing (INSIDE y>0)");
            [self setViewMovedUp:YES];
        }
    }
}


- (void)keyboardWillShow:(NSNotification *)notif
{
    //keyboard will be shown now. depending for which textfield is active, move up or move down the view appropriately
    if (self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    else if (self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}



//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
//NSLog(@"Inside setViewMovedUp");
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5]; // if you want to slide up the view
    CGRect rect = self.view.frame;
    if (movedUp)
    {
NSLog(@"Inside else movedUP YES");
        // 1. move the view's origin up so that the text field that will be hidden come above the keyboard 
        // 2. increase the size of the view so that the area behind the keyboard is covered up.
        rect.origin.y -= kOFFSET_FOR_KEYBOARD;
        rect.size.height += kOFFSET_FOR_KEYBOARD;
    }
    else
    {
NSLog(@"Inside else movedUP NO");
        // revert back to the normal state.
        rect.origin.y += kOFFSET_FOR_KEYBOARD;
        rect.size.height -= kOFFSET_FOR_KEYBOARD;
    }
    self.view.frame = rect;
    [UIView commitAnimations];
}