[Solved] Auto Adjust UITextView and UITextField on appearance on keyboard [duplicate]


This is a fairly common problem, there are all sorts of solutions to it. I put one together and made it part of my EnkiUtils package which you can download from https://github.com/pcezanne/EnkiUtils

Short version: You’ll want to watch for keyboard events and call the Enki keyboardWasShown method, passing it the current view (and cell if you are in a table).

Long Version: Here’s the text from my blog (http://www.notthepainter.com/expose-the-uitextfield-when-keyboard-is-shown/)

Notice that it is a class method, not an instance method. I keep a class called EnkiUtilities around to hold useful things. To call it, we first set up our observer:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWasShown:)
                                             name:UIKeyboardDidShowNotification object:nil];

And in the keyboardWasShown method we call our utilities method:

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    [EnkiUtilities keyboardWasShown:aNotification view:self scrollView:myTableView activeField:activeField activeCell:activeCell];

}

So what is activeField and activeCell? Lets look at our textViewDidBeginEditing method to see how those are set

-(void)textViewDidBeginEditing:(UITextView *)sender
{           
    activeField = sender;

    if ([sender isEqual:descriptionTextView]) {
        activeCell = descriptionCell;
        if (shouldClearDescription) {
            [descriptionTextView initWithLPLStyle:@""];
            shouldClearDescription = false;
        } 
    }else if ([sender isEqual:hintTextView]) {
        activeCell = hintCell;
        if (shouldClearHint) {
            [hintTextView initWithLPLStyle:@""];
            shouldClearHint = false;
        }    
    } else {
        activeCell = nil;
    }
}

This method is called when a UITextField begins editing. I set the activeField to the sender and then I set the activeCell to the cell that corresponds to the field.

The only bit remaining is to restore the view when the keyboard disappears.

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    myTableView.contentInset = contentInsets;
    myTableView.scrollIndicatorInsets = contentInsets;
}

When you are working without a UITableView, just put the text fields into a UIScrollView and pass that, not the UITableView, to keyboardWasShown.

solved Auto Adjust UITextView and UITextField on appearance on keyboard [duplicate]