Weird transition of UILabel in modal during device orientation change

48 Views Asked by At

I'm using autolayout constraints to make an UILabel stay at the top of a modal.

title.topAnchor.constraint(equalTo: view.topAnchor, constant: 10)
title.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 5)
title.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -5)
title.centerXAnchor.constraint(equalTo: view.centerXAnchor)

The modal is presented at the center of the screen and its preferredContentSize is hardcoded as 312 width and 219 height.

However, on my iPhone 11, when my device is being rotated from portrait to landscape, the modal is whiteout firstly, and the UILabel flies into the view before rotation completes(img 1). But when my device is being rotated from landscape back to portrait, the UILabel rotates in place with the screen and never leaves the modal(img 2). Why there is such difference? What can I do to always make the UILabel rotates in place during the orientation change?

enter image description here enter image description here

I feel like it might be related to my constraints but I couldn't figure out why. Could someone please help shed some light? Thanks!

1

There are 1 best solutions below

2
Frankenstein On

Your constraints seem fine, you just have to activate those constraints.

NSLayoutConstraint.activate([
    title.topAnchor.constraint(equalTo: view.topAnchor, constant: 10)
    title.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 5)
    title.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -5)
    title.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])