LoginSignup
5
4

More than 5 years have passed since last update.

SCLAlertViewをキーボードの高さ文ずらす

Last updated at Posted at 2015-03-18

初投稿です。
Swiftを学び始めてまだ間もないので間違ってることもあるかもしれません。間違いがあれば教えてもらえると幸いですm(_ _)m

経緯

iOSで気になるライブラリ Swift編で紹介されているのを見て導入したのですが、TextFieldをおいた時にキーボードでボタンが隠れてしまったので、キーボード表示時に重なったら上にずらす処理を書いてみました。

SCLAlertViewとは

SCLAlertViewはFlatなデザインのAlertViewです。
詳しくは->https://github.com/vikmeup/SCLAlertView-Swift

コード

SCLAlertView.swiftのinitに以下の文を挿入します。

SCLAlertView.swift
public class SCLAlertView: UIViewController {
    required override public init() {
        super.init()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);

    ...
    }
...
}

initでNSNotificationCenter.defaultCenter().addObserverを使うことでキーボードの表示時にkeyboardWillShowが、非表示時にkeyboardWillHideが呼ばれるようになります。あとはSCLAlertViewクラス内に関数の中身を書いてあげましょう。

SCLAlertView.swift
public class SCLAlertView: UIViewController {

    func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            let viewBottom = UIScreen.mainScreen().bounds.size.height - (self.baseView.center.y + kWindowHeight/2)
            let hideHeight = keyboardSize.height - viewBottom + 10
            if  hideHeight > 0 {
                UIView.animateWithDuration(0.2, animations: {
                    self.baseView.center.y -= hideHeight
                })
            }
        }
    }
    func keyboardWillHide(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            if UIScreen.mainScreen().bounds.size.height/2 != self.baseView.center.y {
                UIView.animateWithDuration(0.2, animations: {
                    self.baseView.center.y = UIScreen.mainScreen().bounds.size.height/2
                })
            }
        }
    }

...
}

これでキーボードの高さに合わせてSCLAlertViewが移動するようになります。

参考サイト

【iOS】LINE風チャットUIを実装〜メッセージ入力欄編〜(http://qiita.com/Kaiketch/items/1d0cc3f7bc3aa4d4161a)
SwiftでNSNotificationを利用してクラス間の処理を連携する(http://qiita.com/taka000826/items/2460869a01766fdd221a)
Move textfield when keyboard appears swift(http://stackoverflow.com/questions/25693130/move-textfield-when-keyboard-appears-swift)

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4