我在一个视图控制器上有多个文本字段,并且已经实现了textFieldShouldReturn函数,这样当我点击return时,它就会转到下一个文本字段。但是,现在屏幕保持不变,所以活动文本字段被键盘遮住了。
如何才能使屏幕向下滚动,并且可以看到活动的文本字段?
相关代码:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let nextTextFieldTag = textField.tag + 1
let nextTextField = textField.superview?.viewWithTag(nextTextFieldTag)
if nextTextField != nil {
nextTextField?.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return false
}
发布于 2018-04-02 04:40:07
最简单的方法是使用IQKeyboardManager (https://github.com/hackiftekhar/IQKeyboardManager)
您所需要做的就是将IQKeyboardManager
添加到您的Pod中,安装它并添加初始代码。就这样
从https://github.com/hackiftekhar/IQKeyboardManager复制添加到pod文件
`pod 'IQKeyboardManagerSwift'`
在AppDelegate.swift
中,只需使用import IQKeyboardManagerSwift
框架并启用IQKeyboardManager即可。
import IQKeyboardManagerSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
IQKeyboardManager.sharedManager().enable = true
return true
}
}
如果你想自己做的话。
在您的view.frame.y中,获取活动textfield
textFieldShouldReturn
.y -=
textFieldShouldReturn
或者,您可以将所有文本字段添加到scrollview中,只需简单地更改scrollview.contentOffset.y
发布于 2018-04-02 04:45:51
在UIScrollView中有两种滚动方式:
scrollView.setContentOffset(textField.frame.origin, animated: true)
.scrollView.scrollRectToVisible(textField.frame, animated: true)
发布于 2018-04-02 05:04:01
我假设你所有的文本字段都在滚动视图scrollView
上。现在,您希望下一个文本字段nextTextField
向上滚动。在这种情况下-
在你的if
条件下-
scrollView.contentOffset = CGPoint(x : 0, y : nextTextField.frame.y)
https://stackoverflow.com/questions/49605336
复制