swift 点击Textfield 后自动上移,避免键盘被遮住

一些textfield在键盘显示出来的时候会被挡住,所以在编辑textfield我们可以把视图上移

方法是给textfield增加两个监听事件

    @IBAction func beginEdit(_ sender: UITextField) {
        animateViewMoving(up: true, moveValue: 100)
    }
        
    @IBAction func endEdit(_ sender: UITextField) {
        animateViewMoving(up: false, moveValue: 100)
    }
    
    func animateViewMoving (up:Bool, moveValue :CGFloat){
        let movementDuration:TimeInterval = 0.3
        let movement:CGFloat = ( up ? -moveValue : moveValue)
        UIView.beginAnimations( "animateView", context: nil)
        UIView.setAnimationBeginsFromCurrentState(true)
        UIView.setAnimationDuration(movementDuration )
        self.view.frame = self.view.frame.offsetBy(dx: 0,  dy: movement)
        UIView.commitAnimations()
    }

 

posted on 2017-07-25 11:56  WonderBlog  阅读(2254)  评论(0编辑  收藏  举报