ios - 下一个文本字段开始编辑时视图返回中心
问题描述
我有一个包含 2 个文本字段的视图,并创建了一个自定义 UIView 类,该类在处于编辑模式时管理文本字段定位。
当第一个文本字段开始编辑时,视图会正确定位以避免键盘重叠,但是当我在第一个文本字段处于编辑模式(或键入任何内容)时点击下一个文本字段时,视图会回到中心
这是我的代码:-
class ActiveKeyboardView: UIView {
var distanceBetweenViewAndKeyboard : CGFloat = 10
private var viewOriginalYPoint : CGFloat = 0
override init(frame: CGRect) {
super.init(frame: frame)
self.setUpKeyboardObserver()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setUpKeyboardObserver()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private func setUpKeyboardObserver() {
NotificationCenter.default.addObserver(self, selector: #selector(self.handleKeyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.handleKeyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc private func handleKeyboardWillShow(notification:NSNotification) {
guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else {return}
viewOriginalYPoint = self.frame.origin.y
let viewsBottomPoint = self.frame.origin.y + self.frame.height
let keyboardTop = keyboardFrame.origin.y
if keyboardTop < viewsBottomPoint {
self.frame.origin.y -= (abs(viewsBottomPoint-keyboardTop) + distanceBetweenViewAndKeyboard)
}
}
@objc private func handleKeyboardWillHide(notification:NSNotification) {
guard let keyboardAnimationDuration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else {return}
UIView.animate(withDuration: keyboardAnimationDuration) { [weak self] in
self?.frame.origin.y = (self?.viewOriginalYPoint)!
}
}
}
这是github链接
解决方案
您需要ActiveKeyboardView
嵌入,Scroll View
以便它可以自动滚动ActiveKeyboardView
Textfield
开始编辑。
如果您使用ActiveKeyboardView
Textfield 制作键盘距离,您可以CocoaPods
在项目中使用。
pod 'IQKeyboardManagerSwift'
AppDelegate.swift
您可以在文件中添加行。
import IQKeyboardManagerSwift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
IQKeyboardManager.shared.enable = true
return true
}
如果你想在键盘和 UITextfield 之间建立特定的距离而不是使用线。
IQKeyboardManager.shared.keyboardDistanceFromTextField = 50
推荐阅读
- auth0 - 带有 AuthenticationClient 的 Auth0 登录对话框
- python - 引发“不可编辑”异常
- android - 默认通知文本大小
- parsing - 在 Elixir 中将 JSON 字符串解析为整数
- tensorflow - tensorflow.js 损失无穷大
- python - 如果用户未登录,Shopify 应用程序 OAuth 错误白名单 URL
- tensorflow - Keras 多 gpu 模型尝试在不存在的设备 CPU:1 中分配模型
- joomla - 在 joomla 中使用不同模板的所有页面上使用相同的菜单
- javascript - 如何更新已执行的javascript?
- php - CodeIgniter Undefined 属性加载不起作用