ios – 当键盘存在时如何使UITextField向上移动?

前端之家收集整理的这篇文章主要介绍了ios – 当键盘存在时如何使UITextField向上移动?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何防止键盘隐藏UITextField?

解决方法

我假设这是在UIViewController上发生的.如果是这样,您可以设置在键盘显示/隐藏时调用以下2个函数,并在其块中进行适当响应. @H_403_6@设置UIViewController:

  1. class XXXViewController: UIViewController,UITextFieldDelegate... {
  2.  
  3. var frameView: UIView!
@H_403_6@首先,在ViewDidLoad中:

  1. override func viewDidLoad() {
  2.  
  3. self.frameView = UIView(frame: CGRectMake(0,self.view.bounds.width,self.view.bounds.height))
  4.  
  5.  
  6. // Keyboard stuff.
  7. let center: NSNotificationCenter = NSNotificationCenter.defaultCenter()
  8. center.addObserver(self,selector: #selector(ATReportContentViewController.keyboardWillShow(_:)),name: UIKeyboardWillShowNotification,object: nil)
  9. center.addObserver(self,selector: #selector(ATReportContentViewController.keyboardWillHide(_:)),name: UIKeyboardWillHideNotification,object: nil)
  10. }
@H_403_6@然后实现以下2个函数以响应上面ViewDidLoad中定义的NSNotificationCenter函数.我给你一个移动整个视图的例子,但你也可以只为UITextFields制作动画.

  1. func keyboardWillShow(notification: NSNotification) {
  2. let info:NSDictionary = notification.userInfo!
  3. let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
  4.  
  5. let keyboardHeight: CGFloat = keyboardSize.height
  6.  
  7. let _: CGFloat = info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber as CGFloat
  8.  
  9.  
  10. UIView.animateWithDuration(0.25,delay: 0.25,options: UIViewAnimationOptions.CurveEaseInOut,animations: {
  11. self.frameView.frame = CGRectMake(0,(self.frameView.frame.origin.y - keyboardHeight),self.view.bounds.height)
  12. },completion: nil)
  13.  
  14. }
  15.  
  16. func keyboardWillHide(notification: NSNotification) {
  17. let info: NSDictionary = notification.userInfo!
  18. let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
  19.  
  20. let keyboardHeight: CGFloat = keyboardSize.height
  21.  
  22. let _: CGFloat = info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber as CGFloat
  23.  
  24. UIView.animateWithDuration(0.25,(self.frameView.frame.origin.y + keyboardHeight),completion: nil)
  25.  
  26. }
@H_403_6@不要忘记在离开视图时删除通知

  1. override func viewWillDisappear(animated: Bool) {
  2. NSNotificationCenter.defaultCenter().removeObserver(self,object: nil)
  3. NSNotificationCenter.defaultCenter().removeObserver(self,object: nil)
  4. }

猜你在找的iOS相关文章