简体   繁体   English

键盘出现约束时快速向上移动

[英]Swift-Move view up when keyboard appears with constraints

I am using the following code from "Programming iOS 8". 我正在使用“ Programming iOS 8”中的以下代码。 I have a subview with constraints that contains a simple textfield. 我有一个包含一个简单文本字段的约束子视图。 This view has top and bottom to superview constraints, which I have outlets for. 此视图具有从上到下的超级视图约束,我对此有针对性。 I have an outlet for the subview as well. 我也有该子视图的出口。 The goal here is that when the keyboard appears, it pushes this subview up. 目的是在键盘出现时将其向上推。 I get an error on the line "let f = self.fr!.frame" Thread 1: EXC_BAD_INSTRUCTION. 我在“ let f = self.fr!.frame”这一行上遇到错误:线程1:EXC_BAD_INSTRUCTION。 Does it have to do with needing to unwrap the optional? 它与需要拆开可选件有关吗? Could it be an issue with my constraints? 我的约束可能有问题吗? Any help would be much appreciated. 任何帮助将非常感激。 Thanks. 谢谢。

import UIKit

class ViewController: UIViewController {

@IBOutlet var topSpace: NSLayoutConstraint!
@IBOutlet var bottomSpace: NSLayoutConstraint!
@IBOutlet var slidingView: UIView!
var fr: UIView?

override func viewDidLoad() {
    NSNotificationCenter.defaultCenter().addObserver(
        self, selector: "keyboardShow:",
        name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(
        self, selector: "keyboardHide:",
        name: UIKeyboardWillHideNotification, object: nil)




    super.viewDidLoad()   

}


func textFieldDidBeginEditing(tf: UITextField) {
    self.fr = tf // keep track of the first responder
}

func textFieldShouldReturn(tf: UITextField) -> Bool {

    tf.resignFirstResponder()
    self.fr = nil
    return true

}

func keyboardShow(n:NSNotification) {
    let d = n.userInfo!
    var r = (d[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()
    r = self.slidingView.convertRect(r, fromView:nil)
    let f = self.fr!.frame
    let y : CGFloat =
    f.maxY + r.size.height - self.slidingView.bounds.height + 5
    if r.origin.y < f.maxY {
        self.topSpace.constant = -y
        self.bottomSpace.constant = y
        self.view.layoutIfNeeded()
    }
}

func keyboardHide(n:NSNotification){
    self.topSpace.constant = 0
    self.bottomSpace.constant = 0
    self.view.layoutIfNeeded()
}



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


}

If I'm not mistaken, the keyboard shows before you start editing, so your self.fr is still nil when your keyboard is shown. 如果我没记错的话,键盘会在您开始编辑之前显示,因此显示键盘时self.fr仍然为零。 Check to see if it's nil. 检查是否为零。 It shouldn't have to do anything with the optional unwrapping. 它不需要对可选的展开做任何事情。 It only fails when you unwrap a null. 仅当解开null时,它才会失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM