作り方はNSObserverという物を使う
-(void)viewWillAppear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
-(void)viewWillDisappear:(BOOL)animated{
// observerを取り除く
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
-(void)keyboardWillShow:(NSNotification *)aNotification {
// keyboardが現れたときの処理
CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
// したにあったテキストボックスなどを見えるところまで表示。
// キーボードの大きさを取得する
CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
// prekeyboardHeightはすでにクラス全体で使えるように定義しておく。
if (prekeyboardHeight != keyboardRect.size.height) {
float change = keyboardRect.size.height - prekeyboardHeight;
prekeyboardHeight = keyboardRect.size.height;
keyboardRect.size.height = change;
}
// textFieldを押し上げる。
CGRect textRect = self.text.frame;
textRect.origin.y = textRect.origin.y - keyboardRect.size.height;
self.text.frame = textRect;
NSLog(@"keyboard appear");
}
-(void)keyboardWillHide:(NSNotification *)aNotification {
// keyboardが消えたときの処理
// 今度はキーボードが消えたときに位置を調整する
// キーボードの大きさを取得
CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
if (prekeyboardHeight != keyboardRect.size.height) {
float change = keyboardRect.size.height - prekeyboardHeight;
prekeyboardHeight = keyboardRect.size.height;
keyboardRect.size.height = change;
}
// 全体を押し下げる。
CGRect textRect = self.text.frame;
textRect.origin.y = textRect.origin.y + keyboardRect.size.height;
self.text.frame = textRect;
prekeyboardHeight = 0;
NSLog(@"keyboard disappear");
}
なんでviewDidLoadじゃなくて、viewWillAppearに書いてあるかというと、viewDidLoadに書いたらなんかうまくいかなかったから。 多分、NSNotificationCenterはインスタンスが作られていないとだめみたいな決まりがあるのだろう
No comments:
Post a Comment