简体   繁体   English

在/ other /方向上以及隐藏键盘的情况下获取当前iOS设备的键盘高度

[英]Get keyboard height of current iOS device in the /other/ orientation and whilst the keyboard is hidden

Currently, I know how to get the current keyboard height through notifications, and I'm using that to set various auto layout constraints. 目前,我知道如何通过通知获取当前键盘的高度,并且正在使用它来设置各种自动布局约束。 When the keyboard hides, certain interface elements move down too, whilst remaining the same size. 隐藏键盘时,某些界面元素也会向下移动,同时保持相同的大小。 The size of this is dictated by a UITextView (and the text typed in it), except once it get's too big, scrolling is enabled and it's height is constrained to the current height (so that it doesn't immediately collapse when scrolling is enabled). 此控件的大小由UITextView(以及在其中键入的文本)决定,除非它太大,则启用滚动,并且将其高度限制为当前高度(以便在启用滚动时不会立即折叠) )。 This works nicely when the keyboard disappears. 当键盘消失时,这很好用。 The problem is when the screen rotates. 问题是屏幕旋转时。 There's no longer room for the current fixed height, so the constraints become unsatisfiable. 当前的固定高度不再有空间,因此约束变得无法满足。 To properly update them and know what height the text view should be, I need to know what height the keyboard is in the orientation it's about to rotate to (since the space above it should be equal to this), is there anyway to do that without relying on hardcoded values? 为了正确地更新它们并知道文本视图的高度,我需要知道键盘将要旋转到的方向的高度(因为它上面的空间应该等于此高度),无论如何要这样做不用依赖硬编码的值? (which, even then probably won't work given custom keyboards) (即使在使用自定义键盘的情况下,即使那样也无法使用)

I have considered alternatives to setting the height this way, but every solution I can think of ultimately requires the same keyboard information. 我已经考虑过以这种方式设置高度的替代方法,但是我能想到的每个解决方案最终都需要相同的键盘信息。

Have you considered using content insets? 您是否考虑过使用内容插图? I usually use this, you don't have to worry about constraints at all this way, works for any descendant of UIScrollView 我通常使用它,您完全不必担心约束,它适用于UIScrollView任何后代

// Register for keyboard notifications
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)

// Process notifications
func setScrollViewInsets(insets: UIEdgeInsets) {
        self.textView.contentInset = insets
        self.textView.scrollIndicatorInsets = insets
    }

func keyboardWillChangeFrame(note: NSNotification) {
    if var kbRect = note.userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue() {
        let insets = UIEdgeInsets(top: 0, left: 0, bottom: kbRect.size.height, right: 0)
        self.setScrollViewInsets(insets)
    }
}

func keyboardWillHide(note: NSNotification) {
    let insets = UIEdgeInsetsZero
    self.setScrollViewInsets(insets)
}

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

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