Objective-C
Xcode

textFieldが隠れない!NSNotificationCenterの使い方その1

More than 5 years have passed since last update.

最近つかっているNSNotificationCenterがかなり便利だったのでまとめてみた。

おすすめの使い方はいくつかあるが、その一つを紹介する

今回NSNotificationCenterで主に使うメソッドは以下の2つ


NSNotificationCenter

[[NSNotificationCenter defaultCenter] addObserver: selector: name:object:]

[[NSNotificationCenter defaultCenter] removeObserver: name: object:]

これを使って、キーボートと一緒にせりあがるtextFieldを作れる

実装は以下のとおり。


Keyboard.h

@interface Keyboard : UIViewController

@property (strong, nonatomic) UITextField * textField;
@end


Keyboard.m

@implementation Keyboard

-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];

//キーボード表示・非表示の通知を開始
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}

-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
//キーボード表示・非表示の通知を終了
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Keyboard animation method

- (void)keyboardWillShow:(NSNotification *)aNotification {
//キーボードの高さをとる
CGRect keyboardRect = [[aNotification userInfo][UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardRect = [[self.view superview] convertRect:keyboardRect fromView:nil];
NSNumber *duration = [aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

//アニメーションでtextFieldを動かす
[UIView animateWithDuration:[duration doubleValue]
animations:^{
CGRect rect = self.textField.frame;
rect.origin.y = keyboardRect.origin.y - self.textField.frame.size.height;
self.textField.frame = rect
} ];
}

- (void)keyboardWillHide:(NSNotification *)aNotification {
NSNumber *duration = [aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

//アニメーションでtextFieldを動かす
[UIView animateWithDuration:[duration doubleValue]
animations:^{
CGRect rect = self.textField.frame;
rect.origin.y = self.view.frame.size.height- self.textField.frame.size.height;
self.textField.frame = rect
}];
}

#pragma mark - textField

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
// エンターをおしたら、キーボードを閉じる
[textField resignFirstResponder];

return YES;
}
@end


次 : delegateいらず!NSNotificationCenterの使い方その2