不同iOS设备的键盘高度不同.有人知道如何通过编程获得设备键盘的高度吗?

推荐答案

Swift

您可以通过订阅UIKeyboardWillShowNotification通知来获取键盘高度.(假设您想在显示之前知道高度是多少).

Swift 4

NotificationCenter.default.addObserver(
    self,
    selector: #selector(keyboardWillShow),
    name: UIResponder.keyboardWillShowNotification,
    object: nil
)
@objc func keyboardWillShow(_ notification: Notification) {
    if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height
    }
}

Swift 3

NotificationCenter.default.addObserver(
    self,
    selector: #selector(keyboardWillShow),
    name: NSNotification.Name.UIKeyboardWillShow,
    object: nil
)
@objc func keyboardWillShow(_ notification: Notification) {
    if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height
    }
}

Swift 2

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
func keyboardWillShow(notification: NSNotification) {
        let userInfo: NSDictionary = notification.userInfo!
        let keyboardFrame: NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
        let keyboardRectangle = keyboardFrame.CGRectValue()
        let keyboardHeight = keyboardRectangle.height
    }

Ios相关问答推荐

2024 Beacon应用程序- startMonitoring(适用于:地区)或

如何让AVAudio.installTap()每秒回调125次

SwiftUI文本编辑器内部滚动填充,无需文本裁剪

更改文本在Flutter 中的位置

在SwiftUI中动态隐藏列表的空部分

在金属中设置纹理的UV坐标以编程方式变形纹理

AVFoundation Camera推出变焦SWIFT

通过 Rosetta 打开模拟器 xcode 14 以修复滚动

如何避免任何绑定空错误并更好地获取代码

Xcode 6 App Store 提交失败并显示您的帐户已经拥有有效的 iOS 分发证书

在 iOS 中获取设备位置(仅限国家/地区)

Xcode 缺少支持文件 iOS 12.2 (16E227)

Swift枚举继承

无论我将构建版本或应用程序版本更改为什么,都会出现 ITEMS-4238冗余二进制上传错误

iOS中的apk类似功能是什么?

iOS:以编程方式制作屏幕截图的最快、最高效的方法是什么?

SLComposeViewController 分享教程

'无效更新:第 0 节中的无效行数

从故事板导航到其他 Swift 1.2 文件时 Xcode 6.3 崩溃

具有两种不同字体大小的 NSAttributedString 示例?