键盘遮挡Textfield的解决办法

overridefuncviewDidLoad() {

  super.viewDidLoad()

    //滚动视图的窗口尺寸

         scrollView.frame=CGRect(x:0,y:0,width:self.view.frame.width,height:self.view.frame.height)

//定义滚动视图的内容视图尺寸与窗口尺寸一样

scrollView.contentSize.height=self.view.frame.height

scrollViewHeight=self.view.frame.height

//检测键盘出现或消失的状态

NotificationCenter.default.addObserver(self, selector:#selector(showKeyboard), name:NSNotification.Name.UIKeyboardWillShow, object:nil)

NotificationCenter.default.addObserver(self, selector:#selector(hideKeyboard), name:NSNotification.Name.UIKeyboardWillHide, object:nil)

//声明隐藏虚拟键盘的操作

//创建一个单击手势,当手势发生后会调用hidekeyboardTap方法

let hideTap =UITapGestureRecognizer(target:self, action:#selector(hideKeyboardTap))

//设置该手势的单击次数是1次

hideTap.numberOfTapsRequired=1

//设置了当前控制器的视图为可交互

self.view.isUserInteractionEnabled=true

//将该手势识别添加到控制器上

self.view.addGestureRecognizer(hideTap)

}

func hideKeyboardTap(recognizer:UITapGestureRecognizer){

// UIView的endEditing方法用于设置视图的编辑状态(虚拟键盘呈现在屏幕上)时,执行endEditing(true)可以让虚拟键盘消失

self.view.endEditing(true)

}

funcshowKeyboard(notification:Notification){

//获取userInfo字典中健名为[UIKeyboardFrameEndUserInfoKey]的值并强制转化成NSValue类型并赋值给keyboard

letrect = notification.userInfo! [UIKeyboardFrameEndUserInfoKey]as!NSValue

keyboard= rect.cgRectValue

//当虚拟键盘出现后,将滚动视图的实际高度缩小为屏幕高度减去键盘的高度

UIView.animate(withDuration:0.4){

self.scrollView.frame.size.height=self.scrollViewHeight-self.keyboard.size.height

}

}

funchideKeyboard(notification:Notification){

//当键盘消失后,将滚动视图的实际高度改变为屏幕的高度值

UIView.animate(withDuration:0.4){

self.scrollView.frame.size.height=self.view.frame.height

}

}

你可能感兴趣的:(键盘遮挡Textfield的解决办法)