Saturday, March 13, 2010

Refactoring Suggested items. Moving keyboard helper out.

Moving keyboard helper out


The next segment of code that I currently have in place inside the file is changing the size of a view based on the keyboard appearing or disappearing.  I created a new class KeyboardHelper which is used to do this.  It registers for keyboard notifications and changes the view size as the keyboard appears or disappears (disappears is not currently well tested).

When it is deallocated it will unregister the notifications to help ensure that notifications are not sent.

A future enhancement might be to see if the current view is REALLY active prior to doing frame changes.


header file



A simple header file, only one public method, which initializes this with a view.


// The keyboard helper is an object that when given a view will
// resize that view when the keyboard appears or disappears.   
// The dealloc of this will unregister the notification.
@interface KeyboardHelper : NSObject {

@private
UIView *view;
CGRect originalSize;

}
@property (nonatomic,retain) UIView *view;
@property (nonatomic) CGRect originalSize;


- (id) initWithView:(UIView*) viewToUse;
@end


Source file





The source is also fairly simple
@implementation KeyboardHelper
@synthesize view;
@synthesize originalSize;

- (id) initWithView:(UIView*) viewToUse
{
self.view=viewToUse;

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAppearing:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDisappearing:) name:UIKeyboardWillHideNotification object:nil];
return self;
}

- (void)keyboardDisappearing:(NSNotification *)notification {
view.frame=originalSize;
}

- (void)keyboardAppearing:(NSNotification *)notification {
NSDictionary *keys=[notification  userInfo];
NSValue *value=[keys objectForKey:UIKeyboardBoundsUserInfoKey];
CGRect bounds;
[value getValue:&bounds];
CGRect myFrame=[self.view frame];
originalSize=myFrame;
view.frame=CGRectMake(myFrame.origin.x,myFrame.origin.y,myFrame.size.width,
myFrame.size.height-bounds.size.height);
}

- (void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];

}



Usage




And to use it, do the following:
a) Create a property for the keyboard monitor, the standard (retain,nonatomic).
b) Add the following in viewDidLoad
self.keyboardHelper=[[KeyboardHelper alloc] initWithView:self.suggestions];

where suggestions is the view you want to resize.

To see the changes for this refactoring, check out

No comments:

Post a Comment