ios 如何获得键盘的高度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31774006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get height of Keyboard?
提问by Lachtan
The height of a keyboard on varying iOS devices is different. Does anybody know how I can get height of a device's keyboard programmatically?
不同 iOS 设备上的键盘高度不同。有人知道如何以编程方式获取设备键盘的高度吗?
回答by roc
In Swift:
在斯威夫特:
You can get the keyboard height by subscribing to the UIKeyboardWillShowNotification
notification. (Assuming you want to know what the height will be before it's shown).
您可以通过订阅UIKeyboardWillShowNotification
通知来获取键盘高度。(假设您想在显示之前知道高度是多少)。
Something like this:
像这样的东西:
Swift 2
斯威夫特 2
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
Swift 3
斯威夫特 3
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: NSNotification.Name.UIKeyboardWillShow,
object: nil
)
Swift 4
斯威夫特 4
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification,
object: nil
)
Then you can access the height in keyboardWillShow
function like these:
然后你可以访问keyboardWillShow
函数中的高度,如下所示:
Swift 2
斯威夫特 2
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
}
Swift 3
斯威夫特 3
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
}
}
Swift 4
斯威夫特 4
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
}
}
回答by fs_tigre
Swift 3.0 and Swift 4.1
Swift 3.0 和 Swift 4.1
1- Register the notification in the viewWillAppear
method:
1- 在viewWillAppear
方法中注册通知:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
2- Method to be called:
2-要调用的方法:
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardSize.height
print(keyboardHeight)
}
}
回答by Eduardo Irias
Swift 4 and Constraints
Swift 4 和约束
To your tableview add a bottom constraint relative to the bottom safe area. In my case the constraint is called tableViewBottomLayoutConstraint.
向您的 tableview 添加一个相对于底部安全区域的底部约束。在我的情况下,约束称为 tableViewBottomLayoutConstraint。
@IBOutlet weak var tableViewBottomLayoutConstraint: NSLayoutConstraint!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(notification:)), name: .UIKeyboardWillHide, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow , object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide , object: nil)
}
@objc
func keyboardWillAppear(notification: NSNotification?) {
guard let keyboardFrame = notification?.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyboardHeight: CGFloat
if #available(iOS 11.0, *) {
keyboardHeight = keyboardFrame.cgRectValue.height - self.view.safeAreaInsets.bottom
} else {
keyboardHeight = keyboardFrame.cgRectValue.height
}
tableViewBottomLayoutConstraint.constant = keyboardHeight
}
@objc
func keyboardWillDisappear(notification: NSNotification?) {
tableViewBottomLayoutConstraint.constant = 0.0
}
回答by Jesse
Update Swift 4.2
更新 Swift 4.2
private func setUpObserver() {
NotificationCenter.default.addObserver(self, selector: .keyboardWillShow, name: UIResponder.keyboardWillShowNotification, object: nil)
}
selector method:
选择器方法:
@objc fileprivate func keyboardWillShow(notification:NSNotification) {
if let keyboardRectValue = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardRectValue.height
}
}
extension:
延期:
private extension Selector {
static let keyboardWillShow = #selector(YourViewController.keyboardWillShow(notification:))
}
Update Swift 3.0
更新 Swift 3.0
private func setUpObserver() {
NotificationCenter.default.addObserver(self, selector: .keyboardWillShow, name: .UIKeyboardWillShow, object: nil)
}
selector method:
选择器方法:
@objc fileprivate func keyboardWillShow(notification:NSNotification) {
if let keyboardRectValue = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardRectValue.height
}
}
extension:
延期:
private extension Selector {
static let keyboardWillShow = #selector(YourViewController.keyboardWillShow(notification:))
}
Tip
提示
UIKeyboardDidShowNotification or UIKeyboardWillShowNotification might called twice and got different result, this articleexplained why called twice.
UIKeyboardDidShowNotification 或 UIKeyboardWillShowNotification 可能会调用两次并得到不同的结果,本文解释了为什么会调用两次。
In Swift 2.2
在 Swift 2.2 中
Swift 2.2 deprecates using strings for selectors and instead introduces new syntax: #selector
.
Swift 2.2 不赞成使用字符串作为选择器,而是引入了新的语法:#selector
.
Something like:
就像是:
private func setUpObserver() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: .keyboardWillShow, name: UIKeyboardWillShowNotification, object: nil)
}
selector method:
选择器方法:
@objc private 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
editorBottomCT.constant = keyboardHeight
}
extension:
延期:
private extension Selector {
static let keyboardWillShow = #selector(YourViewController.keyboardWillShow(_:))
}
回答by Alessign
Shorter version here:
更短的版本在这里:
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardSize.height
}
}
回答by ZAFAR007
Swift 4.
斯威夫特 4。
Simplest Method
最简单的方法
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight : Int = Int(keyboardSize.height)
print("keyboardHeight",keyboardHeight)
}
}
回答by Vivek
Swift 5
斯威夫特 5
override func viewDidLoad() {
// Registering for keyboard notification.
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
}
/* UIKeyboardWillShowNotification. */
@objc internal func keyboardWillShow(_ notification : Notification?) -> Void {
var _kbSize:CGSize!
if let info = notification?.userInfo {
let frameEndUserInfoKey = UIResponder.keyboardFrameEndUserInfoKey
// Getting UIKeyboardSize.
if let kbFrame = info[frameEndUserInfoKey] as? CGRect {
let screenSize = UIScreen.main.bounds
//Calculating actual keyboard displayed size, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381)
let intersectRect = kbFrame.intersection(screenSize)
if intersectRect.isNull {
_kbSize = CGSize(width: screenSize.size.width, height: 0)
} else {
_kbSize = intersectRect.size
}
print("Your Keyboard Size \(_kbSize)")
}
}
}
回答by P.T.Dog94
The method by ZAFAR007 updated for Swift 5 in Xcode 10
ZAFAR007 在 Xcode 10 中为 Swift 5 更新的方法
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight : Int = Int(keyboardSize.height)
print("keyboardHeight",keyboardHeight)
}
}
回答by Nrv
// Step 1 :- Register NotificationCenter
// 步骤 1 :- 注册通知中心
ViewDidLoad() {
self.yourtextfield.becomefirstresponder()
// Register your Notification, To know When Key Board Appears.
NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
// Register your Notification, To know When Key Board Hides.
NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
// Step 2 :- These Methods will be called Automatically when Keyboard appears Or Hides
// 步骤 2 :- 当键盘出现或隐藏时这些方法将被自动调用
func keyboardWillShow(notification:NSNotification) {
let userInfo:NSDictionary = notification.userInfo! as NSDictionary
let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
tblViewListData.frame.size.height = fltTblHeight-keyboardHeight
}
func keyboardWillHide(notification:NSNotification) {
tblViewListData.frame.size.height = fltTblHeight
}
回答by Muhammad Asyraf
I had to do this. this is a bit of hackery. not suggested.
but i found this very helpful
I made extension and struct
我不得不这样做。这有点骇人听闻。不建议。
但我发现这很有帮助
我做了扩展和结构
ViewController Extension + Struct
ViewController 扩展 + 结构
import UIKit
struct viewGlobal{
static var bottomConstraint : NSLayoutConstraint = NSLayoutConstraint()
}
extension UIViewController{ //keyboardHandler
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
func listenerKeyboard(bottomConstraint: NSLayoutConstraint) {
viewGlobal.bottomConstraint = bottomConstraint
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
// Register your Notification, To know When Key Board Hides.
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
//Dismiss Keyboard
@objc func dismissKeyboard() {
view.endEditing(true)
}
@objc func keyboardWillShow(notification:NSNotification) {
let userInfo:NSDictionary = notification.userInfo! as NSDictionary
let keyboardFrame:NSValue = userInfo.value(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
UIView.animate(withDuration: 0.5){
viewGlobal.bottomConstraint.constant = keyboardHeight
}
}
@objc func keyboardWillHide(notification:NSNotification) {
UIView.animate(withDuration: 0.5){
viewGlobal.bottomConstraint.constant = 0
}
}
}
Usage:
get most bottom constraint
用法:
获取最底约束
@IBOutlet weak var bottomConstraint: NSLayoutConstraint! // default 0
call the function inside viewDidLoad()
在viewDidLoad() 中调用函数
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboardWhenTappedAround()
listenerKeyboard(bottomConstraint: bottomConstraint)
// Do any additional setup after loading the view.
}
Hope this help.
-you keyboard will now auto close when user tap outside of textfieldand
-it will push all view to above keyboardwhen keyboard appear.
-you could also used dismissKeyboard()when ever you need it
希望这有帮助。
-当用户点击文本字段外时,您的键盘现在将自动关闭,并且
-当键盘出现时,它将把所有视图推送到键盘上方。
- 你也可以在需要的时候使用dismissKeyboard()