View Single Post
  #2 (permalink)  
Old February 28th, 2011, 03:04 PM
thepianoguy thepianoguy is offline
Friend of Wrox
Points: 1,671, Level: 16
Points: 1,671, Level: 16 Points: 1,671, Level: 16 Points: 1,671, Level: 16
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Aug 2010
Posts: 298
Thanks: 1
Thanked 62 Times in 60 Posts
Default

You are correct the book is wrong. The reason it still works should pretty apparent. The observer to the notification is added and never removed. What is removed was never added.

Check the following with the added lines to illustrate:

Code:
//---when the keyboard appears---
-(void) keyboardDidShow:(NSNotification *) notification {
	
	NSLog(@"The notification name is %@",[notification name]);
	if (keyboardIsShown) return;
	
    NSDictionary* info = [notification userInfo];
	
	//---obtain the size of the keyboard---
	NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];	
	CGRect keyboardRect = [self.view convertRect:[aValue CGRectValue] fromView:nil];

	NSLog(@"%f", [aValue CGRectValue].size.height);

	NSLog(@"%f", keyboardRect.size.height);
	
    //---resize the scroll view (with keyboard)---
    CGRect viewFrame = [scrollView frame];
    viewFrame.size.height -= keyboardRect.size.height;
    scrollView.frame = viewFrame;
	
    //---scroll to the current text field---
    CGRect textFieldRect = [currentTextField frame];
    [scrollView scrollRectToVisible:textFieldRect animated:YES];
		
    keyboardIsShown = YES;
}

//---when the keyboard disappears---
-(void) keyboardDidHide:(NSNotification *) notification {
	NSDictionary* info = [notification userInfo];
	
	NSLog(@"The notification name is %@",[notification name]);
	
	//---obtain the size of the keyboard---
    NSValue* aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
	CGRect keyboardRect = [self.view convertRect:[aValue CGRectValue] fromView:nil];
	    
    //---resize the scroll view back to the original size (without keyboard)---
    CGRect viewFrame = [scrollView frame];
    viewFrame.size.height += keyboardRect.size.height;
    scrollView.frame = viewFrame;
	
    keyboardIsShown = NO;
}

-(void) viewWillAppear:(BOOL)animated {    
    //---registers the notifications for keyboard---
	
	static BOOL FirstTime = YES;
	if (FirstTime) {
		NSLog(@"Registering the observer");
    [[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(keyboardDidShow:) 
												 name:UIKeyboardDidShowNotification 
											   object:self.view.window]; 
    
    [[NSNotificationCenter defaultCenter]	 addObserver:self
											  selector:@selector(keyboardDidHide:)
												  name:UIKeyboardDidHideNotification
												object:nil];
		FirstTime = NO;
	}
}
Bob
Reply With Quote
The Following User Says Thank You to thepianoguy For This Useful Post:
gNotapipe (March 1st, 2011)