ios – Swift,移动键盘后面的内容在关闭后不会重置

前端之家收集整理的这篇文章主要介绍了ios – Swift,移动键盘后面的内容在关闭后不会重置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的一个VC中有一个uiscrollview.在scrollView中,我有多个TF,按钮等.我使用下面的代码,根据Apple文档,在调用键盘通知时向上移动scrollView,以推高隐藏的文本字段.但是,当我关闭键盘时,scrollView不会重置或向下移动,它只是停留在“向上移动”的位置.

我在这里错过了什么吗?我有一个名为的类的成员变量:

var activeTextField: UITextField!

我是否正确使用了委托方法

(func registerForKeyboardNotifications() {
    let notificationCenter = NSNotificationCenter.defaultCenter()
    notificationCenter.addObserver(self,selector: "keyboardWillBeShown:",name: UIKeyboardWillShowNotification,object: nil)
    notificationCenter.addObserver(self,selector: "keyboardWillBeHidden:",name: UIKeyboardWillHideNotification,object: nil)
}

func keyboardWillBeShown(sender: NSNotification) {
    let info: NSDictionary = sender.userInfo!
    let value: NSValue = info.valueForKey(UIKeyboardFrameBeginUserInfoKey) as NSValue
    let keyboardSize: CGSize = value.CGRectValue().size
    let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0,0.0,keyboardSize.height,0.0)
    scrollView.contentInset = contentInsets
    scrollView.scrollIndicatorInsets = contentInsets

    // If active text field is hidden by keyboard,scroll it so it's visible
    // Your app might not need or want this behavior.
    var aRect: CGRect = self.view.frame
    aRect.size.height -= keyboardSize.height
    let activeTextFieldRect: CGRect? = activeTextField?.frame
    let activeTextFieldOrigin: CGPoint? = activeTextFieldRect?.origin
    if (!CGRectContainsPoint(aRect,activeTextFieldOrigin!)) {
        scrollView.scrollRectToVisible(activeTextFieldRect!,animated:true)
    }
}

// Called when the UIKeyboardWillHideNotification is sent
func keyboardWillBeHidden(sender: NSNotification) {
    let contentInsets: UIEdgeInsets = UIEdgeInsetsZero
    scrollView.contentInset = contentInsets
    scrollView.scrollIndicatorInsets = contentInsets
}

func textFieldDidBeginEditing(textField: UITextField!) {
    activeTextField = textField
    scrollView.scrollEnabled = true
}

func textFieldDidEndEditing(textField: UITextField!) {
    activeTextField = nil
    scrollView.scrollEnabled = false
}


override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.registerForKeyboardNotifications()
}

override func viewDidDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

解决方法

我这样做了,它对我有用.似乎比你的方式容易多了.我为我的项目使用了UITextView.但它应该与UITextField一样. – / 25只是为了让标题显示出来.
func textViewDidBeginEditing(textView: UITextView) {
    myScrollView.setContentOffset(CGPointMake(0,textView.frame.origin.y-25),animated: true)
}

func textViewDidEndEditing(textView: UITextView) {
    myScrollView.setContentOffset(CGPointMake(0,-textView.frame.origin.y+25),animated: true)
}

猜你在找的iOS相关文章