我有与此相同的问题: iPhone Keyboard with accessory view height problems
但是答案没有新的解决方案,什么也解决不了!
答案 0 :(得分:0)
我找到了一个很好的解决方案Here
进行了很少的更改,并将其更新为 swift 4.2 。
要提的要点
class ViewController: UIViewController {
@IBOutlet weak var inputField: UITextField!
@IBOutlet weak var textFieldBottomContraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
self.setUpKeyBoardNotifications()
self.addToolBarTo(uiElement: self.inputField)
}
func setUpKeyBoardNotifications()
{
NotificationCenter.default.addObserver(self,
selector: #selector(self.keyboardNotification(notification:)),
name: UIResponder.keyboardWillChangeFrameNotification,
object: nil)
}
func addToolBarTo(uiElement element:UITextField)
{
let numberToolbar = UIToolbar(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 45))
numberToolbar.barStyle = .black
numberToolbar.items = [
UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(ViewController.cancelAction)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.doneAction))]
numberToolbar.sizeToFit()
element.inputAccessoryView = numberToolbar
}
@objc func keyboardNotification(notification: NSNotification) {
if let userInfo = notification.userInfo {
let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let endFrameY = endFrame?.origin.y ?? 0
let duration:TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw)
if endFrameY >= UIScreen.main.bounds.size.height {
self.textFieldBottomContraint?.constant = 0.0
} else {
self.textFieldBottomContraint?.constant = endFrame?.size.height ?? 0.0
}
UIView.animate(withDuration: duration,
delay: TimeInterval(0),
options: animationCurve,
animations: { self.view.layoutIfNeeded() },
completion: nil)
}
}
@objc func cancelAction()
{
self.inputField.resignFirstResponder()
}
@objc func doneAction()
{
self.inputField.resignFirstResponder()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}