I have a UIStackView
which is changing axis based on its width. It includes two UView
s only. There is a very easy setup (can be copy/pasted to default Xcode project):
class ViewController: UIViewController {
enum DisplayMode {
case regular
case compact
}
private let stackView = UIStackView(frame: .zero)
private let firstView = UIView(frame: .zero)
private let secondView = UIView(frame: .zero)
private var firstViewWidth: NSLayoutConstraint?
private var secondViewWidth: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: view.topAnchor),
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
firstView.backgroundColor = .red
stackView.addArrangedSubview(firstView)
firstView.heightAnchor.constraint(equalToConstant: 80).isActive = true
firstViewWidth = firstView.widthAnchor.constraint(equalTo: stackView.widthAnchor, multiplier: 1/3)
firstViewWidth?.isActive = true
secondView.backgroundColor = .black
stackView.addArrangedSubview(secondView)
secondView.heightAnchor.constraint(equalToConstant: 80).isActive = true
secondViewWidth = secondView.widthAnchor.constraint(equalTo: stackView.widthAnchor, multiplier: 2/3)
secondViewWidth?.isActive = true
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if view.bounds.width < 400 {
switchMode(.compact)
} else {
switchMode(.regular)
}
}
}
private extension ViewController {
func switchMode(_ mode: DisplayMode) {
switch mode {
case .regular:
stackView.axis = .horizontal
firstViewWidth?.isActive = true
secondViewWidth?.isActive = true
case .compact:
stackView.axis = .vertical
firstViewWidth?.isActive = false
secondViewWidth?.isActive = false
}
}
}
It's working just fine but it's giving me nonsense layout error (all constraints in the output seems fine) while changing from compact to regular:
(
"<NSLayoutConstraint:0x6000002c1c20 UIView:0x7fbd4dc149a0.width == 0.333333*UIStackView:0x7fbd4df02430.width (active)>",
"<NSLayoutConstraint:0x6000002c2170 UIView:0x7fbd4dc14d90.width == 0.666667*UIStackView:0x7fbd4df02430.width (active)>",
"<NSLayoutConstraint:0x6000002f2080 'UISV-canvas-connection' UIStackView:0x7fbd4df02430.leading == UIView:0x7fbd4dc149a0.leading (active)>",
"<NSLayoutConstraint:0x6000002f1c70 'UISV-canvas-connection' H:[UIView:0x7fbd4dc14d90]-(0)-| (active, names: '|':UIStackView:0x7fbd4df02430 )>",
"<NSLayoutConstraint:0x6000002f05f0 'UISV-spacing' H:[UIView:0x7fbd4dc149a0]-(0)-[UIView:0x7fbd4dc14d90] (active)>"
)
Can someone explain why is this happening? Is the dynamic axis a culprit?