Как позиционировать вид, используя привязки Auto Layout вне экрана - PullRequest
0 голосов
/ 06 февраля 2019

Как позиционировать вид с помощью якорей автоматической компоновки за пределами экрана справа?Я хочу оживить его позже в центральное положение.

func setup(){
    _ = firstNameTextField.anchor(nil, 
                                  left: view.leftAnchor, 
                                bottom: lastnameTextField.topAnchor, 
                                 right: view.rightAnchor, 
                           topConstant: 16, 
                          leftConstant: 16, 
                        bottomConstant: 8, 
                         rightConstant: 16, 
                         widthConstant: 0, 
                        heightConstant: 46)
}

1 Ответ

0 голосов
/ 06 февраля 2019

Может быть полезно явно определить ваши ограничения, а не использовать «вспомогательную» функцию ... это может помочь вам понять, что происходит.

Тем не менее, вы хотите *Якорь 1003 * вашего поля должен быть ограничен якорем right вашего вида, который будет выводить его за пределы экрана.Затем вы можете изменить это, чтобы анимировать поле для просмотра ... "сдвиньте его справа".

Для этого создайте ограничение "start" и ограничение "end":

// starting constraint will be leading edge of field 16-pts to the right of view's right edge (off-screen)
firstNameLeadingConstraintStart = firstNameTextField.leadingAnchor.constraint(equalTo: view.trailingAnchor, constant: 16.0)

// ending constraint will be leading edge of field 16-pts from view's left edge
firstNameLeadingConstraintEnd   = firstNameTextField.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16.0)

Чтобы оживить это:

    // de-activate starting constraint
    self.firstNameLeadingConstraintStart.isActive = false

    // activate ending constraint
    self.firstNameLeadingConstraintEnd.isActive = true

    // animate the change
    UIView.animate(withDuration: 0.75, animations: {
        self.view.layoutIfNeeded()
    })

Вот базовый пример.Включает кнопку для запуска анимации:

class SampleViewController: UIViewController {

    var firstNameTextField: UITextField = {
        let v = UITextField()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.borderStyle = .roundedRect
        v.backgroundColor = .orange  // to make it easy to see
        return v
    }()

    var button: UIButton = {
        let v = UIButton()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.setTitle("Tap Me", for: .normal)
        v.setTitleColor(.blue, for: .normal)
        return v
    }()

    // constraint for starting position of field
    var firstNameLeadingConstraintStart: NSLayoutConstraint!

    // constraint for ending position of field
    var firstNameLeadingConstraintEnd: NSLayoutConstraint!

    override func viewDidLoad() {

        view.addSubview(firstNameTextField)

        NSLayoutConstraint.activate([

            // top of field 16-pts from top of view
            firstNameTextField.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16.0),

            // width of field should be width of view minus 32 (16-pts padding on each side)
            firstNameTextField.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.widthAnchor, constant: -32.0),

            // height of field 46-pts
            firstNameTextField.heightAnchor.constraint(equalToConstant: 46.0),

            ])

        // starting constraint will be leading edge of field 16-pts to the right of view's right edge (off-screen)
        firstNameLeadingConstraintStart = firstNameTextField.leadingAnchor.constraint(equalTo: view.trailingAnchor, constant: 16.0)

        // ending constraint will be leading edge of field 16-pts from view's left edge
        firstNameLeadingConstraintEnd   = firstNameTextField.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16.0)

        // activate the starting constraint
        firstNameLeadingConstraintStart.isActive = true

        // add a button so we can trigger the animation
        view.addSubview(button)
        NSLayoutConstraint.activate([
            button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            button.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            ])
        button.addTarget(self, action: #selector(didTap(_:)), for: .touchUpInside)
    }

    func animateField() -> Void {

        // de-activate starting constraint
        self.firstNameLeadingConstraintStart.isActive = false

        // activate ending constraint
        self.firstNameLeadingConstraintEnd.isActive = true

        // animate the change
        UIView.animate(withDuration: 0.75, animations: {
            self.view.layoutIfNeeded()
        })

    }

    @objc func didTap(_ sender: Any) {
        animateField()
    }

}
...