首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将视图高度设置为等于其宽度

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

Stack Overflow用户
提问于 2016-04-17 15:19:27
回答 3查看 5.2K关注 0票数 6

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-04-17 20:48:12

将高宽比约束添加到视图中

​

票数 16
EN

Stack Overflow用户

发布于 2016-04-18 13:32:30

您可以从storyboard或programmatically中将视图高度设置为等于其宽度,为此,您需要在带有乘数1的视图上添加aspect ratio约束。

从故事板您可以在故事板中的销钉工具帮助下添加aspect ratio约束

通过编程您可以尝试下面的代码,它运行良好。

代码语言:javascript
复制
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))
}
票数 1
EN

Stack Overflow用户

发布于 2016-04-17 15:22:58

试试这个:

代码语言:javascript
复制
yourView.translatesAutoresizingMaskIntoConstraints = false
yourView.addConstraint(NSLayoutConstraint(item: yourView, attribute: .Height, relatedBy: .Equal, toItem: yourView, attribute: .Equal, multiplier: 1, constant: yourWidthHere))

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

代码语言:javascript
复制
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
@IBOutlet weak var widthConstraint: NSLayoutConstraint!

并将高度设置为宽度:

代码语言:javascript
复制
heightConstraint.constant = widthConstraint.constant
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36678386

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档