如何在不出错的情况下获得键盘大小?

时间:2015-04-02 14:23:44

标签: ios swift

我有一个位于屏幕底部的文本视图,并希望在用户开始编辑文本视图时将其向上推。我知道如何向上推视图,但由于屏幕尺寸不同,显示屏始终不一样。我想获得键盘的高度,以便在用户编辑时文本视图位于其上方。我在下面有一段代码,但是当我添加以下3行时,应用程序无法构建并给我一个错误。没有这段代码,应用程序运行完美。我得到的错误是" swift编译器错误:预期声明"。这些行进入我的keyboardWillShow函数。

    if let userInfo = sender.userInfo {
        if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            keyboardHeight = keyboardSize.height
        }

所以完整的代码看起来像这样。

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);

}

var isShown: Bool = false
var willHide: Bool = false
var keyboardHeight: CGFloat = 0

func keyboardWillShow(sender: NSNotification) {

    isShown = true

//The following 3 lines seem to be the problem. Somehow the code stops working when I add them.
    if let userInfo = sender.userInfo {
        if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            keyboardHeight = keyboardSize.height
        }

}

func keyboardWillHide(sender: NSNotification) {

    willHide = true

}

func textViewDidBeginEditing(textView: UITextView) {
    if isShown == true {

        self.view.frame.origin.y -= keyboardHeight

    }
}

func textViewDidEndEditing(textView: UITextView) {
    if willHide == true {

        self.view.frame.origin.y += keyboardHeight

    }
}

0 个答案:

没有答案