Reputation: 1
I am using an extension for my auto-layout as such:
extension UIView{
func anchorSize(to view: UIView){
widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
}
func anchor(top: NSLayoutYAxisAnchor?, leading: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, trailing: NSLayoutXAxisAnchor?, padding: UIEdgeInsets = .zero, size: CGSize = .zero){
translatesAutoresizingMaskIntoConstraints = false
if let top = top{
topAnchor.constraint(equalTo: top, constant: padding.top).isActive = true
}
if let leading = leading{
leadingAnchor.constraint(equalTo: leading, constant: padding.left).isActive = true
}
if let trailing = trailing{
trailingAnchor.constraint(equalTo: trailing, constant: padding.right).isActive = true
}
if let bottom = bottom{
bottomAnchor.constraint(equalTo: bottom, constant: padding.bottom).isActive = true
}
if size.width != 0 {
widthAnchor.constraint(equalToConstant: size.width).isActive = true
}
if size.height != 0 {
heightAnchor.constraint(equalToConstant: size.height).isActive = true
}
}
}
However, I've come across an issue in which when displaying my views on different screen sizes the views become squished or simply don't fit. How would I go about resizing the views through auto-layout to fit multiple screen sizes? This is also the code for when I apply the constraints to something like a label:
logo.anchor(top: view.safeAreaLayoutGuide.topAnchor, leading: view.safeAreaLayoutGuide.leadingAnchor, bottom: nil, trailing: view.safeAreaLayoutGuide.trailingAnchor, padding: .init(top: 20, left: 0, bottom: 0, right: 0))
logo.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
subLogo.anchor(top: logo.bottomAnchor, leading: logo.leadingAnchor, bottom: nil, trailing: logo.trailingAnchor, padding: .init(top: 20, left: 0, bottom: 0, right: 0))
subLogo.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
The iPhone 11 is the correct way of how I would auto layout. I really want to universally resize all my views for other devices.
Here are the screenshots of the example devices
Thanks in advance.
Upvotes: 0
Views: 732
Reputation: 144
If you can show what you are actually talking about from screenshots, would help me a lot to see what’s going on.
By the way you are missing translatesAutoresizingMaskIntoConstraints = false
in func anchorSize()
. Also what are you trying to achieve by having a negative padding amount for top?
Upvotes: -1