i have some anchors that should make 5 labels be properly positioned on every orientation. they do work if they start in a specific orientation, however changing the orientation while being in the app makes my labels go off the screen.
heres my code:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label1 = UILabel()
label1.translatesAutoresizingMaskIntoConstraints = false
label1.backgroundColor = UIColor.red
label1.text = "THESE"
label1.sizeToFit()
let label2 = UILabel()
label2.translatesAutoresizingMaskIntoConstraints = false
label2.backgroundColor = UIColor.cyan
label2.text = "ARE"
label2.sizeToFit()
let label3 = UILabel()
label3.translatesAutoresizingMaskIntoConstraints = false
label3.backgroundColor = UIColor.yellow
label3.text = "SOME"
label3.sizeToFit()
let label4 = UILabel()
label4.translatesAutoresizingMaskIntoConstraints = false
label4.backgroundColor = UIColor.green
label4.text = "AWESOME"
label4.sizeToFit()
let label5 = UILabel()
label5.translatesAutoresizingMaskIntoConstraints = false
label5.backgroundColor = UIColor.orange
label5.text = "LABELS"
label5.sizeToFit()
view.addSubview(label1)
view.addSubview(label2)
view.addSubview(label3)
view.addSubview(label4)
view.addSubview(label5)
var previous: UILabel?
for label in [label1, label2, label3, label4, label5] {
label.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
label.heightAnchor.constraint(equalToConstant: view.frame.height / 5 - 10).isActive = true
if let previous = previous {
label.topAnchor.constraint(equalTo: previous.bottomAnchor, constant: 10).isActive = true
} else {
label.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
}
previous = label
}
}
}
i tried using
-setNeedsLayout
-layoutIfNeeded
on orientation change
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
getScreenSize()
}
func getScreenSize(){
view.setNeedsLayout
view.layoutIfNeeded
}
however this did nothing. changing the
func getScreenSize(){
view.setNeedsLayout
view.layoutIfNeeded
}
to print something actually does work which makes me think that
-setNeedsLayout
-layoutIfNeeded
isn't what i actually need to acomplish my goals.
I tried searching for something else to no avail.
Can someone please help me on this issue?