Положение UITextField сбрасывается после панорамирования и закрытия клавиатуры - PullRequest
0 голосов
/ 15 декабря 2018

У меня есть текстовое поле, которое пользователь может перемещать.Он отлично работает, если у вас не открыта клавиатура (то есть textField не активен).Но если клавиатура открыта и вы перемещаете текстовое поле, оно сбрасывается в исходное положение при закрытии клавиатуры.

Все остальные мои жесты (Pinch, Rotate) остаются правильными после закрытия клавиатуры, сбрасывается только позиция.

@objc func addTextField() {
    let textField = UITextField.makeTextField()
    textField.delegate = self

    view.addSubview(textField)
    textField.anchorCenterSuperview()

    textField.becomeFirstResponder()

    addGestures(to: textField)
}

func addGestures(to textField: UITextField) {
    //add pan gesture
    let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
    gestureRecognizer.delegate = self
    textField.addGestureRecognizer(gestureRecognizer)

    //Enable multiple touch and user interaction for textfield
    textField.isUserInteractionEnabled = true
    textField.isMultipleTouchEnabled = true

    //add pinch gesture
    let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(pinchRecognized(pinch:)))
    pinchGesture.delegate = self
    textField.addGestureRecognizer(pinchGesture)

    //add rotate gesture.
    let rotate = UIRotationGestureRecognizer.init(target: self, action: #selector(handleRotate(recognizer:)))
    rotate.delegate = self
    textField.addGestureRecognizer(rotate)
}

@objc func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) {
    if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {
        let translation = gestureRecognizer.translation(in: self.view)
        // note: 'view' is optional and need to be unwrapped
        gestureRecognizer.view!.center = CGPoint(x: gestureRecognizer.view!.center.x + translation.x, y: gestureRecognizer.view!.center.y + translation.y)
        gestureRecognizer.setTranslation(CGPoint.zero, in: self.view)
    }

}

// MARK: Handle Pinch
@objc func pinchRecognized(pinch: UIPinchGestureRecognizer) {
    if let view = pinch.view {
        view.transform = view.transform.scaledBy(x: pinch.scale, y: pinch.scale)
        pinch.scale = 1
    }
}

// MARK: Handle Rotate
@objc func handleRotate(recognizer : UIRotationGestureRecognizer) {
    if let view = recognizer.view {
        view.transform = view.transform.rotated(by: recognizer.rotation)
        recognizer.rotation = 0
    }
}

//MARK:- UIGestureRecognizerDelegate Methods
func gestureRecognizer(_: UIGestureRecognizer,
     shouldRecognizeSimultaneouslyWith shouldRecognizeSimultaneouslyWithGestureRecognizer:UIGestureRecognizer) -> Bool {
    return true
}

private extension UITextField {
    static func makeTextField() -> UITextField {
        let tf = UITextField()
        tf.placeholder = ""
        tf.font = UIFont.boldSystemFont(ofSize: 36)
        tf.textColor = .white
        tf.borderStyle = UITextField.BorderStyle.none
        tf.autocorrectionType = UITextAutocorrectionType.no
        tf.keyboardType = UIKeyboardType.default
        tf.returnKeyType = UIReturnKeyType.done
        tf.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
        tf.backgroundColor = .red
        return tf
    }
}

extension UIView() {
    public func anchorCenterXToSuperview(constant: CGFloat = 0) {
        translatesAutoresizingMaskIntoConstraints = false
        if let anchor = superview?.centerXAnchor {
            centerXAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
        }
    }

     public func anchorCenterYToSuperview(constant: CGFloat = 0) {
        translatesAutoresizingMaskIntoConstraints = false
        if let anchor = superview?.centerYAnchor {
            centerYAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
        }
    }

    public func anchorCenterSuperview() {
        anchorCenterXToSuperview()
        anchorCenterYToSuperview()
    }
}

Исходная позиция

Original Position

Перемещенная позиция с выдвинутой клавиатурой

Moved Position

Когда клавиатура уходит, она возвращается в исходное положение

Reverts to original position

...