首页 > 代码库 > swift 点击Textfield 后自动上移,避免键盘被遮住

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()
    }

 

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