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

如何防止键盘隐藏UITextField?

解决方法

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

设置UIViewController:

class XXXViewController: UIViewController,UITextFieldDelegate... {

    var frameView: UIView!

首先,在ViewDidLoad中:

override func viewDidLoad() {

    self.frameView = UIView(frame: CGRectMake(0,self.view.bounds.width,self.view.bounds.height))


    // Keyboard stuff.
    let center: NSNotificationCenter = NSNotificationCenter.defaultCenter()
        center.addobserver(self,selector: #selector(ATReportContentViewController.keyboardWillShow(_:)),name: UIKeyboardWillShowNotification,object: nil)
    center.addobserver(self,selector: #selector(ATReportContentViewController.keyboardWillHide(_:)),name: UIKeyboardWillHideNotification,object: nil)
}

然后实现以下2个函数以响应上面ViewDidLoad中定义的NSNotificationCenter函数.我给你一个移动整个视图的例子,但你也可以只为UITextFields制作动画.

func keyboardWillShow(notification: NSNotification) {
    let info:NSDictionary = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()

    let keyboardHeight: CGFloat = keyboardSize.height

    let _: CGFloat = info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber as CGFloat


    UIView.animateWithDuration(0.25,delay: 0.25,options: UIViewAnimationoptions.CurveEaseInOut,animations: {
        self.frameView.frame = CGRectMake(0,(self.frameView.frame.origin.y - keyboardHeight),self.view.bounds.height)
        },completion: nil)

}

func keyboardWillHide(notification: NSNotification) {
    let info: NSDictionary = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()

    let keyboardHeight: CGFloat = keyboardSize.height

    let _: CGFloat = info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber as CGFloat

    UIView.animateWithDuration(0.25,(self.frameView.frame.origin.y + keyboardHeight),completion: nil)

}

不要忘记在离开视图时删除通知

override func viewWilldisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self,object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self,object: nil)
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...