我使用以下方法移动我的' UITextView'当用户点击它时。但这适用于iPhone 7和iPhone X,但是当我在iPhone 6,5s上试用它时,textView并没有向上移动。 请帮我正确地移动键盘。
extension UIViewController {
func startAvoidingKeyboard() {
NotificationCenter.default.addObserver(self, selector: #selector(_onKeyboardFrameWillChangeNotificationReceived(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
func stopAvoidingKeyboard() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
@objc private func _onKeyboardFrameWillChangeNotificationReceived(_ notification: Notification) {
if #available(iOS 11.0, *) {
guard let userInfo = notification.userInfo,
let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
return
}
let keyboardFrameInView = view.convert(keyboardFrame, from: nil)
let safeAreaFrame = view.safeAreaLayoutGuide.layoutFrame.insetBy(dx: 0, dy: -additionalSafeAreaInsets.bottom)
let intersection = safeAreaFrame.intersection(keyboardFrameInView)
let animationDuration: TimeInterval = (notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue
let animationCurve = UIViewAnimationOptions(rawValue: animationCurveRaw)
UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: {
self.additionalSafeAreaInsets.bottom = intersection.height
self.view.layoutIfNeeded()
}, completion: nil)
}
}
}
答案 0 :(得分:0)
在iOS 11及更高版本中,您的代码运行正常,但对于早期版本,您应该使用NSNotification.Name.UIKeyboardDidChangeFrame
代替NSNotification.Name.UIKeyboardWillChangeFrame
答案 1 :(得分:0)
请检查iPhone 6,5s的版本。
只有在版本等于11.0或更高版本时才能使用
答案 2 :(得分:0)
你为什么这样做? 我建议每次触摸'UITextView'时使用约束动画为约束设置动画(以便它移动),你可以阅读我给别人的关于如何设置约束动画的答案(here)
你现在听说过CocoaPods吗?您可以使用一些有用的库来为您的应用设置动画(例如HERO)。
如果您不知道什么是可可豆荚或如何安装,请查看此视频(Cocoa Pods Tutorial - How to install and setup Cocoa Pods)
有时候你只想在一种类型的设备上做特定的动画或特定的事情(无论你的头脑中是什么)(只说iPhone 8而不是别的);为此你可以使用Device Kit我建议你阅读它
希望我能够提供帮助
谢谢
答案 3 :(得分:0)
func keyboardWillShow(_ notification: Notification)
{
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
let info: NSDictionary = notification.userInfo! as NSDictionary
let keyboardHeight = ((info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size.height)! + self.extraPadding
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardHeight, 0.0)
self.scrollView?.contentInset = contentInsets
self.scrollView?.scrollIndicatorInsets = contentInsets
}
}
func keyboardWillBeHidden(_ notification: Notification)
{
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
scrollView?.contentInset = contentInsets
scrollView?.scrollIndicatorInsets = contentInsets
}
这是我在显示/隐藏键盘时调整滚动视图的内容区域的方法。您应该能够以相同的方式调整UITextView的内容区域。