LoginSignup
10
15

More than 5 years have passed since last update.

テキストフィールドにキーボードが被らないようにする(色々バージョン)swift3

Last updated at Posted at 2017-06-18

タイトル通りなのですが、テキストフィールドにキーボードを被らないようにする方法です。このやり方人によってそれぞれあるのでパターン化して残して置こうと思いました。結構これ自分的には欲しかったので、もしかしたらと共有して置こうと思います。ちなみにここでコード書くと結構いっぱいあるのでgithubにあげています。コードはクローンしてみていただけたらと思います。:shamrock:

githubのurl → https://github.com/sachiko-kame/swift.sample19

ちなみにプロジェクトはホームに種類書いて
スクリーンショット 2017-06-19 2.54.32.png

遷移先にクラス分けてって書いてます。
スクリーンショット 2017-06-19 2.58.57.png

これを作るにあたって参考にさせていただいたURLです。このクラスはどこのurlを参考にしたかも上に書いてあります。

:hatched_chick:かぶる分だけスクロールしての調整の参考一番のオススメ,ちなみにこれが結構多かった印象受けました。
http://qiita.com/kobaboy/items/d56086b92f84c586562d

:hatched_chick:アニメーションつけてのviewの縮小での調整の参考
http://hacknote.jp/archives/7958/

:hatched_chick:制約を使っての調整の参考
http://hajihaji-lemon.com/smartphone/swift/uitextview_keyboard/

:hatched_chick:AutoLayoutの参考
http://blog.personal-factory.com/2016/01/11/make-auto-layout-via-code/

:hatched_chick:タップでキーボードを閉じるの参考
https://i-app-tec.com/ios/uigesturerecognizer.html

やっぱり一番お気に入りのクラスだけコード乗せておきます!!

pattern2ViewController.swift
//参考URL http://qiita.com/kobaboy/items/d56086b92f84c586562d
class pattern2ViewController: UIViewController ,UITextFieldDelegate, UIScrollViewDelegate {

    var txtActiveField = UITextField()
    var scrollFormer:CGFloat! = nil
    let scrollViewsample = UIScrollView()


    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.blue

        let mainViewFrame = UIScreen.main.bounds

        scrollViewsample.frame = mainViewFrame
        scrollViewsample.contentSize = CGSize(width:mainViewFrame.size.width , height:mainViewFrame.height + 150)
        let sampletextFile = UITextField()
        sampletextFile.delegate = self
        sampletextFile.text = "パターン2"
        sampletextFile.borderStyle = UITextBorderStyle.roundedRect
        sampletextFile.frame.size.width = mainViewFrame.size.width/2
        let rec = CGRect(x: mainViewFrame.midX - sampletextFile.frame.size.width/2, y: 500, width:mainViewFrame.size.width/2 , height:  40.0)
        sampletextFile.frame = rec
        self.view.addSubview(scrollViewsample)
        scrollViewsample.addSubview(sampletextFile)

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillAppear(_ animated: Bool) {

        super.viewWillAppear(animated)

        let notificationCenter = NotificationCenter.default
        notificationCenter.addObserver(self, selector: #selector(pattern2ViewController.handleKeyboardWillShowNotification(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        notificationCenter.addObserver(self, selector: #selector(pattern2ViewController.handleKeyboardWillHideNotification(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()

        return true
    }



    //UITextFieldが編集された直後に呼ばれる.
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {

        //編集されたテキストフィールドを格納しておく
        txtActiveField = textField
        return true
    }

    func handleKeyboardWillShowNotification(_ notification: Notification) {


        let userInfo = notification.userInfo!
        //キーボードの大きさ調べる
        let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let myBoundSize: CGSize = UIScreen.main.bounds.size

        let scrollvalue = scrollViewsample.contentOffset.y
        scrollFormer = scrollViewsample.contentOffset.y

        //入力したテキストフィールドのy軸と高さと少し余白を足してテキストフィールドのマックスy値と少し余白のy軸をとる
        let txtLimit = txtActiveField.frame.maxY + 8.0
        let txtLimit1 = txtActiveField.frame.maxY + 8.0 - scrollvalue

        //現在のselfViewの高さから、キーボードの高さを引いて残りの幅の高さをみるy軸をみる
        let kbdLimit = myBoundSize.height - keyboardScreenEndFrame.size.height


        print("テキストフィールドの下辺:(\(txtLimit))")
        print("キーボードの上辺:(\(kbdLimit))")

        //キーボードよりテキストフィールドのy軸が大きかったらキーボードにかかっている状態。スクロールビューをその分移動させる。
        if txtLimit1 >= kbdLimit {
            scrollViewsample.contentOffset.y = txtLimit - kbdLimit
        }
    }

    func handleKeyboardWillHideNotification(_ notification: Notification) {


        //スクロールしてある位置に戻す
        scrollViewsample.contentOffset.y = scrollFormer
    }


}

10
15
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
10
15