如何为堆栈视图中的视图添加约束 [英] How to Add Constraint for view inside stack view

查看:186
本文介绍了如何为堆栈视图中的视图添加约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含4个按钮的堆栈视图。每个按钮我也添加了subview。那4个按钮的子视图,我尝试编程为其添加约束。一些约束,例如 .Trailing .Leading .Top .Bottom 我无法通过错误约束和堆栈添加它查看问题。如何将该约束添加到stackview的子视图的任何解决方案。如果有任何样品,对我来说真的很好。谢谢提前

I have one stack view that contains with 4 buttons. And each button I also add subview to that. The subview of that 4 buttons, I try to program to add constraint into it. Some constraint such as .Trailing .Leading .Top .Bottom I cannot add to it by error constraint and stack view problem. How any solution to add that constraints to subview of stackview. if have any sample it's really good for me. thank in advance

推荐答案

UIStackView的功能是减少你对约束的使用,只需给它一些设置信息,如轴,分布,对齐,间距。堆栈视图将自动布局您的子视图项,因为堆栈视图的大小基于其子视图intrinsicContentSize,您可以通过额外的约束设置子视图的大小来覆盖。

UIStackView's power is to reduce your using of constrains, just give it some setting info such as axis, distribution, alignment, spacing. stack view will layout your subview item automatically, cause stack view's size is based on its' subviews' intrinsicContentSize, you can set subview's size by extra constraints to override.

添加约束到stackView的子视图与UIView中的其他项目相同。但是不是 StackView方式,你应该关心添加冲突约束。

adding constraints to subview of stackView is the same as other items in UIView. but is not a StackView way, and you should be care about adding conflict constraints.

希望这个代码演示有所帮助:

hope this code demo helps:

let stackView = UIStackView()
let demoView = UIView()
demoView.backgroundColor = UIColor.red

stackView.addArrangedSubview(demoView)
demoView.translatesAutoresizingMaskIntoConstraints = false

// add your constraints as usual
demoView.widthAnchor.constraint(equalToConstant: 300).isActive = true
demoView.heightAnchor.constraint(equalToConstant: 200).isActive = true
demoView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor).isActive = true
demoView.topAnchor.constraint(equalTo: stackView.topAnchor).isActive = true

view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true

这篇关于如何为堆栈视图中的视图添加约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆