Friday 9 May 2014

Code to make a UITextField move up when keyboard appear


// Add a scrollview on main view and add UITextField on that scrollview
-(void) viewDidLoad
{
  UIScrollView  *myScrollView =  [ [UIScrollView  alloc] initWithFrame:           [UIScreen mainScreen ].bounds];
  [myScrollView .contentSize =CGSizeMake(320, 500);
  [myScrollView .contentInset = UIEdgeInsetsMake(0, 0, 60, 0);
  [self.view addSubView:myScrollView ];

  UITextField *myTextField = [ [UITextField  alloc]                             initWithFrame:CGRectMake(20,30,100,33)];
  [myScrollView addSubView:myTextField ];
  myTextField.delegate = self;
}

// Set the scrollview content offset to make the myTextField move up
- (void) textFieldDidBeginEditing:(UITextField *)textField
{
   [myScrollView setContentOffset:CGPointMake(0,textField.center.y-80)           animated:YES]; 
     // here '80' can be any number which decide the height that textfiled     should move
}

//To move the textfield to its original position
- (BOOL) textFieldShouldReturn:(UITextField *)textField
{
    [[myScrollView  setContentOffset:CGPointMake(0,0) animated:YES];
    [textField resignFirstResponder];
    return YES;
}

1 comment: