[英]How to set a view height to be equal to its width
我創建了一個UIView,然后我在uiview上添加了一個約束,它的寬度等於它的superview寬度。 然后我想讓這個uiview的高度等於它的寬度。 我不知道如何添加這種約束。 我可以看到我可以在此視圖上添加高度約束,但如何將其值設置為等於其寬度?
嘗試這個:
yourView.translatesAutoresizingMaskIntoConstraints = false
yourView.addConstraint(NSLayoutConstraint(item: yourView, attribute: .Height, relatedBy: .Equal, toItem: yourView, attribute: .Equal, multiplier: 1, constant: yourWidthHere))
或者,您可以將Width Constraint和Height Constraint的IBOutlet拖到ViewController:
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
@IBOutlet weak var widthConstraint: NSLayoutConstraint!
並將高度設置為寬度:
heightConstraint.constant = widthConstraint.constant
您可以從storyboard
或以programmatically
將視圖高度設置為等於其寬度,因此您需要在具有乘數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))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.