首页 > 解决方案 > 键盘出现时移动视图

问题描述

在屏幕上,我有几个要注册的测试字段。为了使键盘不与字段重叠,我更改了约束。但有一个问题。这些字段出现在不需要的大屏幕上。我怎样才能摆脱它并在真正需要时更改约束。

ViewController.swift

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        NotificationCenter.default.removeObserver(self)
    }
    @objc func keyboardWillShow(notification: NSNotification) {
        var keyboardHeight = CGFloat(0.0)

        if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
            let keyboardRectangle = keyboardFrame.cgRectValue
            keyboardHeight = keyboardRectangle.height
        }

        UIView.animate(withDuration: 3) {

            self.viewBottomConstraint.constant = keyboardHeight + 5
            self.topIconConstraint.constant = 40
            self.view.layoutIfNeeded()
        }
    }

    @objc func keyboardWillHide() {
        self.view.layoutIfNeeded()
        UIView.animate(withDuration: 1) {
            self.viewBottomConstraint.constant = 250
             self.topIconConstraint.constant = 150
            self.view.layoutIfNeeded()
        }
    }

标签: iosswiftconstraints

解决方案


推荐阅读