iPhone scrollView won't scroll after keyboard is closed
- by Rob
I was trying to implement a way to have the UITextField move up when the keyboard opened so that the user could see what they were typing but after implementing the code - it locks my scroll. The view will scroll when the user first gets to that view but after inputting text and closing the keyboard it locks the view. I suspect that it is a problem somewhere in this code:
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSLog(@"Registering for keyboard events");
// Register for the events
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector (keyboardDidShow:)
name: UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector (keyboardDidHide:)
name: UIKeyboardDidHideNotification
object:nil];
// Setup content size
scrollView.contentSize = CGSizeMake(SCROLLVIEW_CONTENT_WIDTH,
SCROLLVIEW_CONTENT_HEIGHT);
//Initially the keyboard is hidden
keyboardVisible = NO;
}
-(void) viewWillDisappear:(BOOL)animated {
NSLog (@"Unregister for keyboard events");
[[NSNotificationCenter defaultCenter]
removeObserver:self];
}
//**-------------------------------**
- (void) keyboardDidShow: (NSNotification *)notif {
NSLog(@"Keyboard is visible");
// If keyboard is visible, return
if (keyboardVisible) {
NSLog(@"Keyboard is already visible. Ignore notification.");
return;
}
// Get the size of the keyboard.
NSDictionary* info = [notif userInfo];
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
// Save the current location so we can restore
// when keyboard is dismissed
offset = scrollView.contentOffset;
// Resize the scroll view to make room for the keyboard
CGRect viewFrame = scrollView.frame;
viewFrame.size.height -= keyboardSize.height;
scrollView.frame = viewFrame;
CGRect textFieldRect = [activeField frame];
textFieldRect.origin.y += 10;
[scrollView scrollRectToVisible:textFieldRect animated:YES];
NSLog(@"ao fim");
// Keyboard is now visible
keyboardVisible = YES;
}
-(void) keyboardDidHide: (NSNotification *)notif {
// Is the keyboard already shown
if (!keyboardVisible) {
NSLog(@"Keyboard is already hidden. Ignore notification.");
return;
}
// Reset the frame scroll view to its original value
scrollView.frame = CGRectMake(0, 0, SCROLLVIEW_CONTENT_WIDTH, SCROLLVIEW_CONTENT_HEIGHT);
// Reset the scrollview to previous location
scrollView.contentOffset = offset;
// Keyboard is no longer visible
keyboardVisible = NO;
}
-(BOOL) textFieldShouldBeginEditing:(UITextField*)textField {
activeField = textField;
return YES;
}
I defined the size above the #imports as:
#define SCROLLVIEW_CONTENT_HEIGHT 1000
#define SCROLLVIEW_CONTENT_WIDTH 320
Really not sure what the issue is.