Простая анимация слайдов в UIView с использованием NSLayoutConstraints - PullRequest
0 голосов
/ 03 мая 2020

Я потратил некоторое время, пытаясь понять это, но я просто не могу. Возможно, здесь есть что-то очень простое, чего мне не хватает. Я пытаюсь оживить вид, поступающий снизу. Вот код, который я использую для представления:

private let undoView: UIView = {
    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = .white
    view.layer.cornerRadius = 15
    view.layer.shadowOffset = .zero
    view.layer.shadowOpacity = 0.3
    view.layer.shadowRadius = 5
    view.layer.shouldRasterize = true
    view.layer.rasterizationScale = UIScreen.main.scale

    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("Undo", for: .normal)
    button.titleLabel?.textAlignment = .center
    button.setTitleColor(.systemBlue, for: .normal)
    let buttonConstraints = [
        button.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
        button.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
        button.topAnchor.constraint(equalTo: view.topAnchor, constant: 16),
        button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16)
    ]
    view.addSubview(button)
    NSLayoutConstraint.activate(buttonConstraints)

    let swipeGesture = UISwipeGestureRecognizer(target: view, action: #selector(undoViewSwiped))
    view.addGestureRecognizer(swipeGesture)

    return view
}()

И вот код, который я использую для достижения анимации:

func addUndoView() {
    var bottomConstraint = undoView.topAnchor.constraint(equalTo: view.bottomAnchor, constant: 0)
    let constraints = [
        undoView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        undoView.widthAnchor.constraint(equalToConstant: view.bounds.width / 3),
        bottomConstraint,
        undoView.heightAnchor.constraint(equalToConstant: 50)
    ]
    view.addSubview(undoView)
    NSLayoutConstraint.activate(constraints)
    undoView.layoutIfNeeded()

    bottomConstraint.isActive = false
    bottomConstraint = undoView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -58)
    bottomConstraint.isActive = true

    UIView.animate(withDuration: 0.5, delay: 0.2, animations: {
        self.undoView.layoutIfNeeded()
    })
}

Я хочу, чтобы представление просто быть создан под видимым видом, а затем сдвиньте до 8 выше нижнего поля макета. Этот код, однако, просто заставляет представление «расширяться» в его окончательной позиции вместо того, чтобы показываться снизу. Использование self.view.layoutIfNeeded () по какой-то причине заставляет вид летать в верхнем левом углу экрана.

1 Ответ

1 голос
/ 03 мая 2020

добрый день. Обычно я работаю со свойством transform для перемещения одного вида из позиции x в часть y, пожалуйста, проверьте этот пример.


class ViewController: UIViewController {

    let button : UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("Button", for: .normal)
        button.backgroundColor = .gray
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    let customView : UIView = {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = .red
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        view.addSubview(button)
        view.addSubview(customView)
        NSLayoutConstraint.activate([
            button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
            button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            customView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
            customView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
            customView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            customView.heightAnchor.constraint(equalToConstant: 100)
        ])
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        setupAnimationCustomView()
    }

    private func setupAnimationCustomView(){
        UIView.animate(withDuration: 1, delay: 0 , options: .curveEaseOut, animations: {
            print(self.button.frame.origin.y)
            let translationY = self.view.frame.height - self.button.frame.origin.y - self.button.frame.height - self.customView.frame.height - 8
            self.customView.transform = CGAffineTransform(translationX: 0, y:  translationY * (-1))

        }, completion: nil)
    }

}


в анимации. Я рассчитываю расстояние, необходимое для перемещения моего customView. .

...