Как прокрутить UITextField, когда он прячется за клавиатурой на Swift4? - PullRequest
0 голосов
/ 19 мая 2018

У меня классическая проблема: клавиатура iOS скрывает UITextField внизу экрана.Таким образом, решение в сети решается только для <= Swift3.Итак, как мне решить эту проблему в Swift4? </p>

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

enter image description here

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

enter image description here

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

Ответы [ 6 ]

0 голосов
/ 19 мая 2018

Если вы следуете этому среднему сообщению, вот ваше решение:

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

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

enter image description here

0 голосов
/ 19 мая 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()

}
0 голосов
/ 19 мая 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 

}
0 голосов
/ 19 мая 2018

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

Ваш средний почтовый рефренс

0 голосов
/ 19 мая 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
    }

}
0 голосов
/ 19 мая 2018

вы можете использовать фреймворк для легкой обработки. То есть IQKeyboardManager

...