UITextViewをキーボードのサイズに合わせてリサイズするサンプル

August 23, 2014

こんにちは。久しぶりのObjective-Cの投稿です。今日は、最近Objective-Cを始めた方とお話をする機会があり、UITextViewをキーボードのサイズに合わせてリサイズするサンプルコードを書きました。

Objective-Cを初めて少しするとこの辺りでハマることは割と一般的だと思います。

環境

  • UIStoryboardとAutoLayoutを利用しています。
  • Xcodeは5.1.1を利用しています。

コード

GitHubにアップしました。

やっていることは、

  • UIKeyboardWillShowNotification
  • UIKeyboardWillChangeFrameNotification
  • UIKeyboardWillHideNotification

の3つの通知を受けて、そこからキーボードのサイズを取得して、それに合わせて制約の値を変えているだけです。これが最適な書き方かわかりませんが。

通知を受けた場合すべて下記のメソッドが呼ばれるようになっています。Hideの時は閉じる。それ以外はキーボードのサイズに合わせてTextViewの大きさを変えています。

- (void)fitKeyboardSize:(NSNotification *)notification { NSString *name = notification.name; NSDictionary *userInfo = notification.userInfo;

if (\[name isEqualToString:UIKeyboardWillHideNotification\]) {
    self.textViewBottomConstraint.constant = ViewControllerTextViewBottomConstraintDefault;
    return;
}

CGFloat duration = \[userInfo\[UIKeyboardAnimationDurationUserInfoKey\] floatValue\];
NSUInteger curve = \[userInfo\[UIKeyboardAnimationCurveUserInfoKey\] integerValue\];
CGRect rect = \[userInfo\[UIKeyboardFrameEndUserInfoKey\] CGRectValue\];

self.textViewBottomConstraint.constant = CGRectGetHeight(rect) + ViewControllerKeyboardUpperMargin;

\[UIView animateWithDuration:duration delay:0.0 options:curve animations:^{
    \[self.view layoutIfNeeded\];
} completion:^(BOOL finished) {
    
}\];

}

今回はTextViewのサイズ変更にしましたが、UIScrollViewなどのサイズ変更をするケースが多いかもしれませんが、それも同じような考え方で実現できると思います。

Swift

Swift版は作成していませんが、考え方は同じなので、コードを脳内変換すればSwiftでも動きます。


Profile picture

Written by morizotter who lives and works in Tokyo building useful things. You should follow them on Twitter