天天看点

弹出键盘时遮挡输入框的问题解决

在进行输入框的动作时,经常会弹出键盘时,遮挡住输入框,所以特意去搜了一下,发现是一个动画的效果 下面增上代码

添加两个输入框,随后 设置代理

在 didbeginediting中 加入代码

func textFieldDidBeginEditing(textField: UITextField) {
        let animationDuration = NSTimeInterval(0.3)
        UIView.beginAnimations("ResizeForKeyBoard", context: nil)
        UIView.setAnimationDuration(animationDuration)
        //上移单位
        let rect = CGRectMake(0, -130, width, height)
        self.view.frame = rect
        UIView.commitAnimations()
    }
           

随后再点击屏幕时,屏幕下滑,因此再设置一个动画,将view设置为uicontrol,随后关联事件touch down

let animationDuration = NSTimeInterval(0.3)
        UIView.beginAnimations("ResizeForKeyBoard", context: nil)
        UIView.setAnimationDuration(animationDuration)
        //上移单位
        let rect = CGRectMake(0, -130, width, height)
        self.view.frame = rect
        UIView.commitAnimations()
           

整体的代码如下

class ViewController: UIViewController,UITextFieldDelegate {
let animationDuration = NSTimeInterval(0.3)
    var width = CGFloat()
    var height = CGFloat()
   @IBOutlet weak var MiMa: UITextField!
    @IBOutlet weak var zhangHao: UITextField!
    override func viewDidLoad() {
        self.width = self.view.frame.size.width
        self.height = self.view.frame.size.height

        super.viewDidLoad()
        //状态栏的白色字体
        self.zhangHao.delegate = self
        self.MiMa.delegate = self
        // Do any additional setup after loading the view, typically from a nib.
    }
//进行编辑时 输入框向上移
    @IBAction func click() {
        zhangHao.resignFirstResponder()
        MiMa.resignFirstResponder()
        UIView.beginAnimations("ResizeForKeyBoard", context: nil)
        UIView.setAnimationDuration(animationDuration)
        let rect = CGRectMake(0, 0, width, height)
        self.view.frame = rect
        UIView.commitAnimations()
    }
    func textFieldDidBeginEditing(textField: UITextField) {
        let animationDuration = NSTimeInterval(0.3)
        UIView.beginAnimations("ResizeForKeyBoard", context: nil)
        UIView.setAnimationDuration(animationDuration)
        //上移单位
        let rect = CGRectMake(0, -130, width, height)
        self.view.frame = rect
        UIView.commitAnimations()
    }

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