As I am doing the Swift program, I am also concerned about warning, so please let me ask you a question without thinking.
I have laid out the UIView on the storyboard and placed it using Constraints.
I would like to change the position and size of the UIView when the UIView is turned to the horizontal screen.
However, if you specify Constraints, it will not change even if you specify the location and size such as frame.
Therefore, I delete Constraints and specify them in the program, but Ambiguos Layout warning occurs.
This is because the location has not been identified.
In this case, how do you program proficient people?
1. I don't care about Ambiguos Layout warning
2. There's something programmed to do without warning.
I am posting expecting 2.Please let me know if anyone knows.
swift
All you have to do is set a constraint that satisfies the layout for the horizontal screen.
In my recent implementation, NSLayoutConstraint for vertical screen and NSLayoutConstraint for horizontal screen are placed in an array, and the isActive
property is set to true
/false
when the screen changes orientation.
add
Here is a sample code:
import UIKit
classViewController:UIViewController {
var portraitConstaints: NSLayoutConstraint = [ ]
var landscapeConstaints: NSLayoutConstraint = [ ]
override func viewDidLoad(){
super.viewDidLoad()
let subview = UIView (frame: CGRect (x:0, y:0, width:100, height:100))
subview.translatesAutoresizingMaskIntoConstraints=false
self.view.addSubview(subview)
subview.backgroundColor=.blue
// common vertical and horizontal constraints
subview.leftAnchor.constraint(equalTo:self.view.safeAreaLayoutGuide.leftAnchor).isActive=true
subview.topAnchor.constraint(equalTo:self.view.safeAreaLayoutGuide.topAnchor).isActive=true
// Vertical screen constraints (subview in top half of screen)
portraitConstaints = [
subview.rightAnchor.constraint(equalTo:self.view.safeAreaLayoutGuide.rightAnchor),
subview.heightAnchor.constraint(equalTo:self.view.safeAreaLayoutGuide.heightAnchor, multiplier:0.5)
]
// Horizontal screen constraints (subview is placed in the left half of the screen)
landscapeConstaints = [
subview.widthAnchor.constraint(equalTo:self.view.safeAreaLayoutGuide.widthAnchor, multiplier:0.5),
subview.bottomAnchor.constraint(equalTo:self.view.safeAreaLayoutGuide.bottomAnchor)
]
// Enable vertical screen constraints for initial conditions (correct if horizontal screen starts)
portraitConstaints.forEach {(cons)in
cons.isActive=true
}
}
override func viewWillTransition(to size:CGSize, with coordinator:UIViewControllerTransitionCoordinator) {
super.viewWillTransition (to:size, with:coordinator)
let portrait = size.height>size.width
portraitConstaints.forEach {(cons)in
cons.isActive=portrait
}
landscapeConstains.forEach {(cons)in
cons.isActive=!portrait
}
coordinator.animate(alongsideTransition: {(_)in
self.view.layoutIfNeeded()
}) {(_)in
}
}
}
© 2024 OneMinuteCode. All rights reserved.