Лучше всего вызывать .layoutIfNeeded () до или после изменения ограничений - PullRequest
0 голосов
/ 11 января 2020

У меня есть кнопка, которая меняет размеры в зависимости от определенных ситуаций. Мне не нужна анимация, потому что пользователь никогда не видит изменения. Иногда при переключении с меньшего размера на больший размер застревает кнопка меньшего размера. Я думаю, что layoutIfNeeded() решит проблему.

Вопрос в том, в какой момент я должен вызвать layoutIfNeeded() в функции setCameraButtonToNormalSize() ниже?

lazy var cameraButton: UIButton = {
    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.addTarget(self, action: #selector(cameraButtonPressed), for: .touchUpInside)
    return button
}()

let normalSize: CGFloat = 50
let smallerSize: CGFloat = 5

var cameraButtonWidthConstraint: NSLayoutConstraint?
var cameraButtonHeightConstraint: NSLayoutConstraint?

func setCameraButtonToNormalSize() {

    // before the constraints are changed

    cameraButtonWidthConstraint?.isActive = false
    cameraButtonHeightConstraint?.isActive = false

    cameraButtonWidthConstraint = cameraButton.widthAnchor.constraint(equalToConstant: normalSize)
    cameraButtonWidthConstraint?.isActive = true
    cameraButtonHeightConstraint = cameraButton.heightAnchor.constraint(equalToConstant: normalSize)
    cameraButtonHeightConstraint?.isActive = true

    // after the constraints are changed
}

fileprivate func setCameraButtonToSmallerSize() {

    cameraButtonWidthConstraint?.isActive = false
    cameraButtonHeightConstraint?.isActive = false

    cameraButtonWidthConstraint = cameraButton.widthAnchor.constraint(equalToConstant: smallerSize)
    cameraButtonWidthConstraint?.isActive = true
    cameraButtonHeightConstraint = cameraButton.heightAnchor.constraint(equalToConstant: smallerSize)
    cameraButtonHeightConstraint?.isActive = true
}

1 Ответ

0 голосов
/ 11 января 2020

Вам нужно позвонить после

// after the constraints are changed
 self.view.layoutIfNeeded()
...