简体   繁体   English

以编程方式向UIView或UIViewController添加约束?

[英]Programmatically add constraints to UIView or UIViewController?

I'm working without Interface Builder. 我没有Interface Builder。 I have a custom view that extends UIView, and a custom controller that extends UIViewController. 我有一个扩展UIView的自定义视图和一个扩展UIViewController的自定义控制器。

My question is - should I add constraints in UIView.updateConstraints, or in UIViewController.viewDidLoad? 我的问题是-我应该在UIView.updateConstraints还是UIViewController.viewDidLoad中添加约束?

It seems like UIView.updateConstraints is the right place, but then I see a lot of code examples where people to it in UIViewController.viewDidLoad. 似乎UIView.updateConstraints是正确的地方,但是随后我在UIViewController.viewDidLoad中看到了很多代码示例。 In addition, if I want to constrain against topLayoutGuide, that's a property on the viewController...so now I have to figure out how to get access to the viewController in the view. 另外,如果我想限制topLayoutGuide,那是viewController的属性...所以现在我必须弄清楚如何在视图中访问viewController。 Yuck. uck

But it just doesn't seem right to do layout (view type work) in the viewController. 但是在viewController中进行布局(视图类型工作)似乎并不正确。 If you were using IB for example, the constraints are added to the view. 例如,如果您使用的是IB,则约束将添加到视图中。

Any suggestions? 有什么建议么?

If the constraints scope are inside the view then place it within updateConstraints . 如果约束范围在视图内部,则将其放在updateConstraints

Also please also explore updating constraints in View controllers 另外,还请探索View控制器中的更新约束

 -(void) updateViewConstraints

method. 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何以编程方式将约束添加到以编程方式创建的UIView? - How to add constraints programmatically to a programmatically created UIView? 以编程方式将 UIView 连接到 UIViewController? - Attach a UIView to a UIViewController programmatically? UIView以编程方式设置约束 - UIView Setting Constraints Programmatically 为什么我以编程方式添加的UIView没有连接到UIViewController? - Why is my UIView that I add programmatically not connected to my UIViewController? 如何添加UIViewController作为在以编程方式创建的UIView中创建的UIButton操作的目标? - How to add UIViewController as target of UIButton action created in programmatically created UIView? 尝试以编程方式在SWIFT中的约束下向滚动视图内添加UIView失败 - Failing at trying to add a UIView inside a scroll view programmatically with constraints in SWIFT 使用自动布局隐藏UIView时以编程方式添加约束 - Add constraints programmatically when hiding a UIView using Auto Layout 在UIViewController上方添加UIView - Add `UIView` above `UIViewController` 通过UIViewController以编程方式实现UIView - Implementing programmatically UIView over a UIViewController 以编程方式超越UIView约束 - Out of bounds UIView constraints programmatically
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM