如何在 iOS 中使用硬件键盘?
How to work with hardware keyboard in iOS?
我正在制作一个简单的 iOS 项目,其中有一个 UITextField
并使用 XCode 模拟器对其进行测试。我还向我的 textField 添加了一个 inputAccessoryView
(一个带有 "Done" 按钮的简单 UIToolBar
)。
当我在模拟器的硬件首选项中打开 Connect Hardware Keyboard
选项并单击文本字段时,键盘没有出现,但工具栏出现(看起来很奇怪 - 没有键盘的工具栏)。在这种情况下,键盘仅在我单击 Toggle Software Keyboard
时出现(默认值:⌘ + K)。当我 关闭 Connect Hardware Keyboard
选项时,程序正常工作,键盘随其工具栏一起出现和消失。我只想在这两种情况下都有正确的行为(例如,不显示带有硬件键盘的工具栏)。
检测当前使用的键盘(软件或硬件)的最简单方法是什么?
代码如下:
import UIKit
class ViewController: UIViewController {
@IBOutlet var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let toolBar = UIToolbar(frame: CGRect(origin: .zero, size: .init(width: view.frame.size.width, height: 30)))
let doneButton = UIBarButtonItem(title: "Done", style: .done
, target: self, action: #selector(doneButtonAction))
toolBar.setItems([doneButton], animated: false)
toolBar.sizeToFit()
textField.inputAccessoryView = toolBar
}
@objc func doneButtonAction() {
self.view.endEditing(true)
}
}
如果我理解正确,这是正确的行为。
您希望在点击 UITextField 时看到 UIToolBar,因为您可能在 Done 按钮上具有更复杂的功能。当然,您不能在硬件键盘上使用该工具栏。
这就是为什么在连接硬件键盘时只打开工具栏的原因。
我正在制作一个简单的 iOS 项目,其中有一个 UITextField
并使用 XCode 模拟器对其进行测试。我还向我的 textField 添加了一个 inputAccessoryView
(一个带有 "Done" 按钮的简单 UIToolBar
)。
当我在模拟器的硬件首选项中打开 Connect Hardware Keyboard
选项并单击文本字段时,键盘没有出现,但工具栏出现(看起来很奇怪 - 没有键盘的工具栏)。在这种情况下,键盘仅在我单击 Toggle Software Keyboard
时出现(默认值:⌘ + K)。当我 关闭 Connect Hardware Keyboard
选项时,程序正常工作,键盘随其工具栏一起出现和消失。我只想在这两种情况下都有正确的行为(例如,不显示带有硬件键盘的工具栏)。
检测当前使用的键盘(软件或硬件)的最简单方法是什么?
代码如下:
import UIKit
class ViewController: UIViewController {
@IBOutlet var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let toolBar = UIToolbar(frame: CGRect(origin: .zero, size: .init(width: view.frame.size.width, height: 30)))
let doneButton = UIBarButtonItem(title: "Done", style: .done
, target: self, action: #selector(doneButtonAction))
toolBar.setItems([doneButton], animated: false)
toolBar.sizeToFit()
textField.inputAccessoryView = toolBar
}
@objc func doneButtonAction() {
self.view.endEditing(true)
}
}
如果我理解正确,这是正确的行为。 您希望在点击 UITextField 时看到 UIToolBar,因为您可能在 Done 按钮上具有更复杂的功能。当然,您不能在硬件键盘上使用该工具栏。 这就是为什么在连接硬件键盘时只打开工具栏的原因。