Tags

, , , , , , , , ,

Introduction

During some JSON framework testing I found interesting problem, on screen keyboard was hiding one of text fields. Trying to figure out how to fix this problem I found two approaches, basically both are using same technique, move view up when keyboard is shown and return it to original position when keyboard is dismissed. First, cleaner approach, uses UIScrollView to do moving also recommended in Text, Web, and Editing Programming Guide for iOS under “Moving Content That Is Located Under the Keyboard”. Second approach is to use plain UIView and do moving manually. For production purpose I will definitely use first, but now I wanted to give a chance to second.

Idea

I will create simple project that will contain four text fields and one text view. All five elements will report to single view controller via UITextFieldDelegate and UITextViewDelegate. On textFieldDidBeginEditing and textViewDidBeginEditing view is moved if needed. When textFieldDidEndEditing and textViewDidEndEditing are triggered view will be moved to original position. On screenshots given bellow implemented functionality is shown. On first screen all five elements are shown, on second screen keyboard is active and text field with text: “test 4” is edited.

screenscreen with keyboard shown

Code

Showing textFieldDidBeginEditing:

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    NSLog(@"textViewDidBeginEditing"); 

    if (textView.frame.origin.y + textView.frame.size.height > 480 - 216) {
        double offset = 480 - 216 - textView.frame.origin.y - textView.frame.size.height - 20;
        CGRect rect = CGRectMake(0, offset, self.view.frame.size.width, self.view.frame.size.height);

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];

        self.view.frame = rect;

        [UIView commitAnimations];
    }    
}

And textViewDidEndEditing:

- (void)textViewDidEndEditing:(UITextView *)textView
{
    NSLog(@"textViewDidEndEditing");

    CGRect rect = CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height);

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

    self.view.frame = rect;

    [UIView commitAnimations];     
}

Also, hideKeyboard is used to hide keyboard when “Done” is pressed ( all text fields are calling this selector on “Did End On Exit”.

- (IBAction)hideKeyboard:(id)sender
{
    NSLog(@"hideKeyboard");
    [sender resignFirstResponder];
}

Source code is available on my GitHub under iOS Playground repo. Project is called OnKeyboardViewResize.

Advertisements