Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a view height to be equal to its width

I created a UIView, then I added a constrain on the uiview that its width is equal to its superview width. Then I want to make this uiview's height to be equal to it's width. I don't know how to add this kind of constrain. I can see that I can add a height constrain on this view but how to set its value to be equal to its width?

like image 461
Joey Yi Zhao Avatar asked Apr 17 '16 15:04

Joey Yi Zhao


2 Answers

Add the Aspect Ratio constraint to your viewenter image description here

like image 55
Olga Nesterenko Avatar answered Oct 17 '22 01:10

Olga Nesterenko


you can set a view height to be equal to its width either from storyboard or programmatically for this you need to add the aspect ratio constraint on a view with multiplier 1.

From storyboard you can add the aspect ratio constraint with the help of Pin Tools in storyboard

By programmatically you can try below code, It is working fine.

override func viewDidLoad() {
    super.viewDidLoad()

    let myView = UIView()
    myView.backgroundColor = UIColor.redColor()
    self.view.addSubview(myView)
    myView.translatesAutoresizingMaskIntoConstraints = false

    // here I'm setting the CenterX & CenterY constraint equal to its superview CenterX & CenterY
    view.addConstraint(NSLayoutConstraint(item: myView, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0))
    view.addConstraint(NSLayoutConstraint(item: myView, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0))

    // here I'm setting the width constraint equal to its superview width
    view.addConstraint(NSLayoutConstraint(item: myView, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 1, constant: 0))

    // here I'm setting the aspect ratio constraint to equal width or height of myView
    // since  aspect ratio constraint belongs to self width or height so add this constraints it self(i.e. myView) but not in its superView
    myView.addConstraint(NSLayoutConstraint(item : myView, attribute: .Width, relatedBy: .Equal, toItem: myView, attribute: .Height, multiplier: 1, constant: 0))
}
like image 21
keshav vishwkarma Avatar answered Oct 17 '22 01:10

keshav vishwkarma