问题很明显,当用户看到键盘正在阻止他们想要键入的文本框而不是按回车键或关闭键盘并点击下一个字段时,他们试图平移到下一个领域。由于我的内容与iPad的大小相匹配,因此当用户尝试平移时,滚动视图不会自动滚动。老实说,我不希望它滚动,除非键盘在屏幕上。希望能够手动滚动以在键盘上方拉文本框
但是,在滚动视图上启用滚动并不能解决问题;即使在这种情况下,它仍然不会响应平移。使viewcontroller不是scrollview的委托并覆盖函数scrollViewDidScroll。我如何获得滚动视图以启用平移,特别是只有在启用键盘时才启用平移。
由于解决方案已经张贴完全不是那么回事,我想我会后我的keyboardWillBeShown和keyboardWillBeHidden代码:
func keyboardWillBeShown(_ sender: Notification)
{
self.myScrollView.isScrollEnabled = true
let info: NSDictionary = (sender as NSNotification).userInfo! as NSDictionary
let value: NSValue = info.value(forKey: UIKeyboardFrameBeginUserInfoKey) as! NSValue
let keyboardSize: CGSize = value.cgRectValue.size
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0)
self.myScrollView.contentInset = contentInsets
self.myScrollView.scrollIndicatorInsets = contentInsets
self.myScrollView.scrollRectToVisible(self.myScrollView.frame, animated: true)
var aRect: CGRect = self.view.frame
aRect.size.height -= keyboardSize.height
let activeTextFieldRect: CGRect? = activeField?.frame
let activeTextFieldOrigin: CGPoint? = activeTextFieldRect?.origin
if activeTextFieldOrigin != nil
{
if (!aRect.contains(activeTextFieldOrigin!))
{
let scrollpoint : CGPoint = CGPoint(x: 0.0, y: activeField!.frame.origin.y - keyboardSize.height)
self.myScrollView.setContentOffset(scrollpoint, animated: true)//.scrollRectToVisible((activeField?.frame)!, animated: true)
}
}
}
func keyboardWillBeHidden(_ sender: Notification)
{
myScrollView.isScrollEnabled = false
let contentInsets: UIEdgeInsets = UIEdgeInsets.zero
myScrollView.contentInset = contentInsets
myScrollView.scrollIndicatorInsets = contentInsets
}
嗨,非常感谢您花时间回复我的帖子。不过,我确实发现,我已经解决了比您发布的代码更多的问题。我只需要解决能够平移和返回的额外问题(如果用户点击返回,我的代码将滚动到屏幕的上半部分(如有必要),因此平移是我需要解决的唯一问题)。 –
嗨,你有没有尝试添加'UITextFieldDelegate'到你的ViewController并添加函数'textFieldShouldReturn'? – Kiester