I build all my objects and labels programmatically and have a function called setupLayout()
which looks like this:
private func setupLayout() {
//The Image that presents the Logo of the chosen cryptocurrency.
view.addSubview(cryptoIconImage)
cryptoIconImage.translatesAutoresizingMaskIntoConstraints = false
cryptoIconImage.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
cryptoIconImage.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true
cryptoIconImage.widthAnchor.constraint(equalToConstant: 60).isActive = true
cryptoIconImage.heightAnchor.constraint(equalToConstant: 60).isActive = true
//The Label that presents the name of the chosen cryptocurrency.
view.addSubview(cryptoLabel)
cryptoLabel.translatesAutoresizingMaskIntoConstraints = false
cryptoLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
cryptoLabel.topAnchor.constraint(equalTo: cryptoIconImage.bottomAnchor, constant: 10).isActive = true
cryptoLabel.font = customFont?.withSize(32)
}
This keeps the layout nice and centered and works well for portraits, and it also works in landscape to do the same. The problem is when in landscape, I don't want the elements centered anymore, I want to move some to the left side of the screen, and some to the right (I didn't show all the items in setup) any other answers to this question all seem to use storyboards, and I have found this method to use:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
let orient = UIApplication.shared.statusBarOrientation
print(orient)
switch orient {
case .portrait:
print("Portrait")
break
// Do something
default:
print("LandScape")
// Do something else
self.landscapeLayout()
break
}
}
But I am not sure how I should go about changing removing and adding new contsraints, so that it works smoothly when going back and forth. I thought about having a landscape layout function() like:
private func landscapeLayout() {
view.addSubview(cryptoIconImage)
cryptoIconImage.translatesAutoresizingMaskIntoConstraints = false
//Removing centerXAnchor
cryptoIconImage.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = false
cryptoIconImage.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true
cryptoIconImage.widthAnchor.constraint(equalToConstant: 60).isActive = true
cryptoIconImage.heightAnchor.constraint(equalToConstant: 60).isActive = true
//Putting it to the left side
cryptoIconImage.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30).isActive = true
}
But This gives me problems with stretching and such, and getting rid of the labels content as it adds them new. How should I go about have 2 seperate layouts between portrait and landscape?