【发布时间】:2019-05-03 10:51:54
【问题描述】:
我想在ViewController 中更新UIKeyboardAppearance。我的意思是说,VC 加载了UIKeyboardAppearance.default。如果我按下一个按钮,我希望键盘更新为.dark,并让键盘现在显示在与.dark 相同的VC 中。
据我所知,iOS 在加载 VC 时会检查 UIKeyboardAppearance 的值,并且在再次加载 VC 之前不会再次检查。即使您更改 UIKeyboardAppearance 的值并隐藏/显示键盘。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// creating a simple text box, and making the placeholder text the value of the keyboardAppearance
myTextBox.backgroundColor = UIColor.lightGray
myTextBox.frame = CGRect(x: 30, y: 200, width: 300, height: 50)
view.addSubview(myTextBox)
UITextField.appearance().keyboardAppearance = .dark
myTextBox.becomeFirstResponder()
myTextBox.placeholder = "Keybaoard Appearance is: \(UITextField.appearance().keyboardAppearance.rawValue)"
// a simple button to toggle the keyboardAppearance
toggleButton.frame = CGRect(x: 30, y: 300, width: 300, height: 50)
toggleButton.setTitle("Toggle Keyboard", for: .normal)
toggleButton.backgroundColor = UIColor.red
toggleButton.addTarget(self, action: #selector(toggleButtonFunction), for: .touchUpInside)
view.addSubview(toggleButton)
}
// toggles the keyboardAppearance. Hides the keyboard, and a second later shows it again.
@objc func toggleButtonFunction() {
if UITextField.appearance().keyboardAppearance == .dark {
UITextField.appearance().keyboardAppearance = .default
}
else {
UITextField.appearance().keyboardAppearance = .dark
}
myTextBox.resignFirstResponder()
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
self.myTextBox.becomeFirstResponder()
self.myTextBox.placeholder = "Keybaoard Appearance is: \(UITextField.appearance().keyboardAppearance.rawValue)"
})
}
let myTextBox = UITextField()
let toggleButton = UIButton()
}
我希望在更改 UIKeyboardAppearance 并隐藏/显示键盘后,它会以新外观(.dark 或 .default)显示,但它会继续以相同的外观显示,直到再次加载 VC .您可以看到 UIKeyboardAppearance 的值发生了变化,但 iOS 似乎在 VC 再次加载之前不会检查该更新。
有没有办法在 VC 中强制重新检查?
感谢您的帮助!
【问题讨论】:
标签: ios swift uiviewcontroller uikeyboard