如何将视图高度设置为等于其宽度

时间:2016-04-17 15:19:28

标签: ios xcode uiview autolayout

我创建了一个UIView,然后我在uiview上添加了一个约束,它的宽度等于它的超视宽度。然后我想让这个uiview的高度等于它的宽度。我不知道如何添加这种约束。我可以看到我可以在此视图上添加高度约束但是如何将其值设置为等于其宽度?

3 个答案:

答案 0 :(得分:8)

将纵横比约束添加到您的视图enter image description here

答案 1 :(得分:0)

试试这个:

yourView.translatesAutoresizingMaskIntoConstraints = false
yourView.addConstraint(NSLayoutConstraint(item: yourView, attribute: .Height, relatedBy: .Equal, toItem: yourView, attribute: .Equal, multiplier: 1, constant: yourWidthHere))

或者您可以将宽度约束和高度约束的IBOutlet拖到ViewController:

@IBOutlet weak var heightConstraint: NSLayoutConstraint!
@IBOutlet weak var widthConstraint: NSLayoutConstraint!

并将高度设置为宽度:

heightConstraint.constant = widthConstraint.constant

答案 2 :(得分:0)

您可以将视图高度设置为等于storyboardprogrammatically的宽度,因此您需要在具有乘数1的视图上添加aspect ratio约束。

从故事板,您可以在故事板中Pin Tools的帮助下添加aspect ratio约束

通过编程,您可以尝试以下代码,它运行正常。

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))
}