我创建了一个UIView,然后对uiview添加了一个约束,它的宽度等于它的superview宽度。然后我想让这个uiview的高度和它的宽度相等。我不知道如何添加这种约束。我可以在这个视图上添加一个高度约束,但是如何将它的值设置为等于它的宽度呢?
发布于 2016-04-17 20:48:12
将高宽比约束添加到视图中

发布于 2016-04-18 13:32:30
您可以从storyboard或programmatically中将视图高度设置为等于其宽度,为此,您需要在带有乘数1的视图上添加aspect ratio约束。
从故事板您可以在故事板中的销钉工具帮助下添加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))
}发布于 2016-04-17 15:22:58
试试这个:
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.constanthttps://stackoverflow.com/questions/36678386
复制相似问题