按下时如何使 textView 位于键盘顶部?

How can I make a textView sit on top of the keyboard when pressed?

我的其中一个视图底部有一个文本视图,如果我什么都不做,它会在弹出时被键盘隐藏。我所做的是,当键盘即将出现时,文本视图向上移动了 160 点。问题是由于大小不同,它不会在每个 iPhone 上都位于完全相同的位置。我想知道文本视图是否有可能位于键盘上方 20 点,而不是将其从原点向上推 160 点。

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

func keyboardWillShow(sender: NSNotification) {

    isShown = true

}

func keyboardWillHide(sender: NSNotification) {

    willHide = true

}

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

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

    }
}

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

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

    }
}

您可以从通知对象中获取键盘的大小。

像这样

NSDictionary* info = [sender userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

您可以在 Apple Docs

中阅读更多相关信息