首页 > 解决方案 > 下一个文本字段开始编辑时视图返回中心

问题描述

我有一个包含 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链接

标签: iosswiftkeyboard

解决方案


您需要ActiveKeyboardView嵌入,Scroll View以便它可以自动滚动ActiveKeyboardView Textfield开始编辑。

如果您使用ActiveKeyboardViewTextfield 制作键盘距离,您可以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

推荐阅读