Friday, May 27, 2011

Simple UIScrollView



Vision
To create a simple example showing how to use a UIScrollView. The scroll view will scroll up when a textfield needs to be moved up to accommodate the keyboard.

Implementation Summary
1. Add a function to listen to keyboard notifications: UIKeyboardWillHideNotification , UIKeyboardDidShowNotification

- (void)registerForKeyboardNotifications
{

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

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];

}
2. Scroll the view above the Text Field being hidden by the keyboard

- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);

UIScrollView *scrollView = (UIScrollView *)self.view;

scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;

CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;

if (!CGRectContainsPoint(aRect, textField.frame.origin) ) {

CGPoint scrollPoint = CGPointMake(0.0, (textField.frame.origin.y+60)-kbSize.height);
[scrollView setContentOffset:scrollPoint animated:YES];

}

3. Scroll the view down once the Keyboard input is complete

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{

UIScrollView *scrollView = (UIScrollView *)self.view;
UIEdgeInsets contentInsets = UIEdgeInsetsZero;

scrollView.contentInset = contentInsets; scrollView.scrollIndicatorInsets = contentInsets;
}

Implementation Example
1. Project Setup

1.1 Create a new View-Based Application




1.1 Name and create the project Simple-UIScrollView


2. Create the Outlets in the Scroll View's implementation

2.1 Update Simple_UIScrollViewViewController.h to include an outlet for a UIDatePicker and a UITextField in addition to making the controller a delegate for UITextFieldDelegate and UIPickerViewDelegate:

#import

@interface Simple_UIScrollViewViewController : UIViewController {
UIDatePicker *datePicker;
UITextField *textField;
}

@property (nonatomic, retain) IBOutlet UIDatePicker* datePicker;
@property (nonatomic, retain) IBOutlet UITextField* textField;
@end

2.1 Synthesize the methods in the implementation file(Simple_UIScrollViewViewController.m)
2.2 Use the UITextFieldDelegates textFieldShouldReturn function to resign first responder and allow the keyboard to disappear(Simple_UIScrollViewViewController.m)
2.3 Code extract of implementation file Simple_UIScrollViewViewController.m(changes highlighted in bold):

#import "Simple_UIScrollViewViewController.h"

@implementation Simple_UIScrollViewViewController

@synthesize datePicker, textField;

- (void)dealloc
{
[super dealloc];
}

- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.

[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad
{
[super viewDidLoad];
} */
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - #pragma mark Text Delegate methods
- (BOOL)textFieldShouldReturn:(UITextField *)aTextField
{
//This removes the keyboard input
[aTextField resignFirstResponder];

return TRUE;
}


@end
3. Create the Scroll View
3.1 Remove the existing View



3.2 Add the scroll view from the objects list
3.3 Connect the outlets:
3.3.1 For the "File's Owner" connect the view outlet to the scroll view




3.3.2 For the scroll view connect the "delegate" outlet to the "File's Owner"




3.3.3 Now the scroll view is the view that will be displayed when the application is run. Run the application to ensure there are no issues.

3.4 Increase the Width and Height of the scroll view to 320 x 367
3.5 From the object selection list add a "Date Picker" to the top half of the window



3.6 From the object selection list add a "Text Field" to the bottom half of the window
3.6.1 Set the "Delegate" outlet of the "Text Field" to the "File's Owner"



3.7 Set the "File's Owner" outlets
3.7.1 textField outlet to the "Text Field"
3.7.2 datePicker outlet to the "Date Picker"
3.7.3 Interface builder should now look like:



3.8 Run the application to confirm all the parts
3.8.1 By selecting the text field the keyboard appears but hides the Text Field.
3.8.2 View before the "Text Field" is selected



3.8.3 View after the "Text Field" is selected (Notice that the Text Field is hidden)



4. Scroll the view when the text field is selected
4.1 Implement the (void) registerForKeyboardNotifications method
4.1.1 Register methods to be called by the selectors(keyboardWasShown and keyboardWillBeHidden)when the keyboard was shown and when the keyboard disappears. The scroll view will use the notifications to determine the scroll effect
- (void)registerForKeyboardNotifications
{

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

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];

}
4.2 Create the method to be calle when the keyboard is shown
4.2.1 The method determines where the location of the text field is and then scrolls the view up to accomodate the keyboard

- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);

UIScrollView *scrollView = (UIScrollView *)self.view;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;

CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;

if (!CGRectContainsPoint(aRect, textField.frame.origin) ) {

CGPoint scrollPoint = CGPointMake(0.0, (textField.frame.origin.y+60)-kbSize.height);
[scrollView setContentOffset:scrollPoint animated:YES];

}

}
4.3 Create the method to be called when the keyboard is hidden
4.3.1 The method scrolls the view back down to accomodate the removal of the keyboard

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{

UIScrollView *scrollView = (UIScrollView *)self.view;
UIEdgeInsets contentInsets = UIEdgeInsetsZero;

scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}

4.3 Setup the keyboard notification to listen when the view gets loaded

- (void)viewDidLoad
{
[super viewDidLoad];
[self registerForKeyboardNotifications];
}

4.3 Run and test the application.

4.3.1 Application loaded


4.3.2 Keyboard selected



4.3.3 Keyboard returned



Built Using
UIScrollView (ios 2.0 later)
ios 4.0


References
Simple UIScrollView source code

http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html#//apple_ref/doc/uid/TP40009542-CH5-SW1

No comments:

Post a Comment