简体   繁体   中英

Autolayout programmatic aspect ratio setting

I am trying to add a subview to view and define autolayout constraints, including aspect ratio. But aspect ratio that I see at runtime is not what I defined in constraints. What am I doing wrong? As you can see in code, background view height should be 0.5 of background view width, but that's not the case here in the screenshot. Here is my code:

class ViewController: UIViewController {

private var backgroundView:UIView?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    view.backgroundColor = UIColor.orange

    backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
    backgroundView?.backgroundColor = UIColor.black.withAlphaComponent(1.0)
    backgroundView?.layer.borderColor = UIColor.white.cgColor
    backgroundView?.layer.borderWidth = 1.5
    backgroundView?.layer.cornerRadius = 4
    backgroundView?.clipsToBounds = true
    backgroundView?.translatesAutoresizingMaskIntoConstraints = false

    view.addSubview(backgroundView!)

    backgroundView?.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.0).isActive = true
    backgroundView?.heightAnchor.constraint(equalTo: backgroundView!.widthAnchor, multiplier: 0.5).isActive = true
    backgroundView?.centerXAnchor.constraint(equalTo: view!.centerXAnchor, constant: 0).isActive = true
    backgroundView?.topAnchor.constraint(equalTo: view!.topAnchor, constant: 4).isActive = true
}


 }

Here is the screenshot:

在此处输入图片说明

"background view height should be 0.5 of background view width"

Your screenshot size is 1334 x 750

Your backgroundView - including the border - is 1334 x 667

1334 * 0.5 == 667

So, you are getting exactly what you are asking for.

Try to change height constraint to set:

backgroundView?.heightAnchor.constraint(equalTo: view!.heightAnchor, multiplier: 0.5).isActive = true

NB: You are getting the exact result which you are looking for. It has the height that's half of its width. There is nothing wrong with the screenshot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM