1. 程式人生 > >鍵盤彈起,遮擋輸入框

鍵盤彈起,遮擋輸入框

 

方式一:

extension LoginViewController:UITextFieldDelegate {

    func textFieldShouldReturn(textField: UITextField) -> Bool {

        textField.resignFirstResponder()

        //鍵盤收回,view放下

        UIView.animateWithDuration(0.4, animations: {

            self.view.frame.origin.y = 0

        })

        return true

    }

    func textFieldDidBeginEditing(textView:UITextField) {

        //view彈起跟隨鍵盤,高可根據自己定義

        UIView.animateWithDuration(0.4, animations: {

            self.view.frame.origin.y = -150

        })

    }

}

方式二:

// 鍵盤改變

    func textFieldDidBeginEditing(textField: UITextField) {

        animateViewMoving(true, moveValue: 300)

    }

    func textFieldDidEndEditing(textField: UITextField) {

        animateViewMoving(false, moveValue: 300)

    }

    func animateViewMoving (up:Bool, moveValue :CGFloat){

        dispatch_after(UInt64(0.3), dispatch_get_main_queue()) {

            let movement:CGFloat = ( up ? -moveValue : moveValue)

            UIView.beginAnimations( "animateView", context: nil)

            UIView.setAnimationBeginsFromCurrentState(true)

            self.view.frame = CGRectOffset(self.view.frame, 0,  movement)

            UIView.commitAnimations()

        }

    }

// 點選輸入框收起鍵盤

    func textFieldShouldReturn(textField: UITextField) -> Bool {

        //收起鍵盤

        textField3.resignFirstResponder()

        //打印出文字框中的值

        print(textField3.text)

        return true

    }

    // 點選螢幕收起鍵盤

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        view.endEditing(true)

    }