Как прокручивать UITextField, когда скрывается клавиатурой на Swift4?

У меня классическая проблема: эта клавиатура iOS скрывает UITextField внизу экрана. Итак, решение в сети решает только ‹= ​​Swift3. Итак, как я могу решить эту проблему в Swift4?

Полноэкранный:

введите здесь описание изображения

Клавиатура скрывает мой UITextField:

введите здесь описание изображения

Я пробовал эту статью: https://medium.com/@dzungnguyen.hcm/autolayout-for-scrollview-keyboard-handling-in-ios-5a47d73fd023 Но self.constraintContentHeight.constant «не является членом» ViewController.


person Augusto    schedule 19.05.2018    source источник


Ответы (6)


Если вы следите за этой средней публикацией, вот ваше решение:

self.constraintContentHeight.constant, который вы не получаете, на самом деле является IBOutlet для ограничения высоты вашего представления содержимого.

поэтому вам нужно установить соединение с этим. Вот и все. Наслаждайтесь!

введите здесь описание изображения

person guru    schedule 19.05.2018

вы можете использовать структуру, чтобы легко справиться. Это IQKeyboardManager

person Niraj Paul    schedule 19.05.2018
comment
Я не хотел бы использовать третьи библиотеки, есть ли в мире кто-нибудь, кто не пользуется? - person Augusto; 19.05.2018

Вам просто нужно обновить [UIKeyboardFrameBeginUserInfoKey] до [UIKeyboardFrameEndUserInfoKey], это даст вам высоту клавиатуры + панель клавиатуры (если она включена).

Ссылка на вашу запись в Medium

person Mr.Kushwaha    schedule 19.05.2018

Вот код, который я использую лично. Это NSLayoutContraint. В раскадровке вы можете выбрать Bottom Layout Guide и изменить его класс на KeyboardNSLayoutConstraint.

import UIKit

public class KeyboardNSLayoutConstraint: NSLayoutConstraint {

    private var offset : CGFloat = 0
    private var keyboardVisibleHeight : CGFloat = 0

    override public func awakeFromNib() {
        super.awakeFromNib()

        offset = constant

        NotificationCenter.default.addObserver(self, selector: #selector(KeyboardLayoutConstraint.keyboardWillShowNotification(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(KeyboardLayoutConstraint.keyboardWillHideNotification(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    @objc func keyboardWillShowNotification(_ notification: Notification) {
        if let userInfo = notification.userInfo {
            if let frameValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
                let frame = frameValue.cgRectValue
                keyboardVisibleHeight = frame.size.height
                 //If device is an iPhone X, it changes the layout constraint to accomodate for the bottom bar
                if (UIDevice.current.modelName == "iPhone10,3") || (UIDevice.current.modelName == "iPhone10,6") {
                    keyboardVisibleHeight = keyboardVisibleHeight - 34
                }
            }

            self.updateConstant()
            switch (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber) {
            case let (.some(duration), .some(curve)):

                let options = UIViewAnimationOptions(rawValue: curve.uintValue)

                UIView.animate(withDuration: TimeInterval(duration.doubleValue), delay: 0, options: options, animations: {                            UIApplication.shared.keyWindow?.layoutIfNeeded()
                        return
                }, completion: { finished in })
            default:

                break
            }

        }

    }

    @objc func keyboardWillHideNotification(_ notification: NSNotification) {
        keyboardVisibleHeight = 0
        self.updateConstant()

        if let userInfo = notification.userInfo {

            switch (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber) {
            case let (.some(duration), .some(curve)):

                let options = UIViewAnimationOptions(rawValue: curve.uintValue)

                UIView.animate(withDuration: TimeInterval(duration.doubleValue), delay: 0, options: options, animations: {
                    UIApplication.shared.keyWindow?.layoutIfNeeded()
                    return
                }, completion: { finished in })
            default: break
            }
        }
    }

    func updateConstant() {
        self.constant = offset + keyboardVisibleHeight
    }

}
person Aléxein andrós    schedule 19.05.2018

Возьмите выход из topConstraint, который является супервизором текстового поля, чем напишите некоторый код в методе делегата, подобном этому

func textFieldShouldBeginEditing(textField: UITextField) -> Bool {

if textfield==txt1{

containerView(superview of textfield).topConstraint.constraint = -100 (According to you choice)

} else if textfield == txt2{

containerView(superview of textfield).topConstraint.constraint = -120 (According to you choice)


}

}



func textFieldDidEndEditing(textField: UITextField) {

containerView(superview of textfield).topConstraint.constraint = 0 

}
person Niraj Paul    schedule 19.05.2018

Вам нужно добавить событие наблюдателя, что клавиатура изменится, что лучше.

extension UIView {


    func bindToKeyboard() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    @objc func keyboardWillChange(_ notification: Notification) {
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let curveFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let deltaY = targetFrame.origin.y - curveFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
            self.frame.origin.y += deltaY
        }, completion: nil)

    }
}

После этого просто вызовите его в viewDidLoad (), но убедитесь, что вы должны установить для него делегат.

override func viewDidLoad() {
    super.viewDidLoad()

    // Textfield delegation
    emailTextField.delegate = self
    passwordTextField.delegate = self

    view.bindToKeyboard()

}
person seyha    schedule 19.05.2018