How to update the UI when the device orientation changed in Swift?

Solution 1:

Actually by using

loginView.frame = CGRect(origin: .zero, size: view.bounds.size)

you assign a frame to your login view which will not change on device rotation.

you might wanna use a constraint approach here as well:

// try replacing
// loginView.frame = CGRect(origin: .zero, size: view.bounds.size)

// with
 loginView.translatesAutoresizingMaskIntoConstraints = false
 NSLayoutConstraint.activate([
    loginView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
    loginView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
    loginView.topAnchor.constraint(equalTo: view.topAnchor),
    loginView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
 ])

Another approach would be updating the frame of your login view e.g.

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
   super.traitCollectionDidChange(previousTraitCollection)
   loginView.frame = CGRect(origin: .zero, size: view.bounds.size)
}

Last but not least you can use autoresizingMask in viewDidLoad

loginView.frame = CGRect(origin: .zero, size: view.bounds.size)
loginView.autoresizingMask = [.flexibleHeight, .flexibleWidth]

P.S. My previous comment was misleading since the login frame wasn't set in the setupStackView() function

and my final comment:

// you can replace
loginView.frame = CGRect(origin: .zero, size: view.bounds.size)
// with
loginView.frame = view.bounds