aaronium112
aaronium112

Reputation: 3088

How do I get a UITableView to scroll up to accommodate a keyboard?

Can anyone explain how to get these methods to work? They compile fine but they don't do anything.

I want to have my tableView scroll so that my keyboard fits nicely.

The solutions posted for this problem are resetting contentSizes and subscribing to NSNotfication. These three methods look like they should do what I'm looking for but nothing happens.

[self.myTable setContentOffset:CGPointMake(0, -100) animated:YES];

[self.myTable selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];

[self.myTable scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];

Upvotes: 0

Views: 3128

Answers (2)

runmad
runmad

Reputation: 14886

Your posted code is quite incomplete to debug what you're doing wrong, since it only exists of a few parts of what's needed. Please see if this is the solution you're looking for?

In your init method add the following:

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

Add this in your implementation (also add to the header file):

- (void)keyboardWillShow:(NSNotification *)notification {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
#endif
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_3_2
        NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
#else
        NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey];
#endif
        CGRect keyboardBounds;
        [keyboardBoundsValue getValue:&keyboardBounds];
        UIEdgeInsets e = UIEdgeInsetsMake(0, 0, keyboardBounds.size.height, 0);
        [[self tableView] setScrollIndicatorInsets:e];
        [[self tableView] setContentInset:e];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
    }
#endif
}

And finally in your dealloc method, add:

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];

This code is from the ASIAuthenticationDialog class from Ben Copsey's ASIHTTPRequest wrapper. Hope it helps.

Upvotes: 3

WrightsCS
WrightsCS

Reputation: 50707

You can use setFrame to make the size of the UITableView half the size of the screen.

Upvotes: 0

Related Questions