gpt4 book ai didi

ios - 使用 iOS Auto Layout 在 subview Controller 和它的父 View 之间建立约束

转载 作者:可可西里 更新时间:2023-11-01 03:33:14 24 4
gpt4 key购买 nike

在我的 Root View Controller 中,我添加了一个 subview Controller 的 View 作为 subview ,如下所示:

ChildViewController *cvc = [[ChildViewController alloc] init];
[self addChildViewController:cvc];
[self.view addSubview:cvc.view];
[cvc didMoveToParentViewController:self];

我现在想使用 NSLayoutConstraint 将 cvc.view 定位在父 View (self.view) 中,这样 cvc.view 就会定位在父 View 底部上方 25 pts 的位置。我的理解是以下应该有效:

UIView *superview = self.view;
UIView *childview = cvc.view;
NSLayoutConstraint *cn =
[NSLayoutConstraint withItem:childview
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:superview attribute:NSLayoutAttributeBottom
multiplier: 1.0
constant: -25.0];
[superview addConstraint: cn];

但是约束在运行时失败了。我最初认为 subview 中的自动调整大小掩码可能会导致问题(并遵循 WWDC 2012 自动布局介绍视频),所以我设置了 [childview setTranslatesAutoresizingMaskIntoConstraints:NO],但随后 subview 就失败了出现。

我做错了什么?

最佳答案

我不确定,但以下应该有效,或者非常相似的东西:

UIView *superview = self.view;
UIView *childview = cvc.view;
NSDictionary *constrainedViews = NSDictionaryOfVariableBindings(childview);
NSArray *constraints =
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[childview]-25-|"
options:0
metrics:nil
views:constrainedViews];

如果不确定您实际上是在为 subview 设置大小,例如:

UIView *superview = self.view;
UIView *childview = cvc.view;
NSDictionary *constrainedViews = NSDictionaryOfVariableBindings(childview);
NSArray *constraints =
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[childview]|"
options:0
metrics:nil
views:constrainedViews];

比如说,让它填满 View 的宽度。或者:

UIView *superview = self.view;
UIView *childview = cvc.view;
NSDictionary *constrainedViews = NSDictionaryOfVariableBindings(childview);
NSArray *constraints =
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[childview(>100,<304)]-|"
options:0
metrics:nil
views:constrainedViews];

这意味着像 childview 这样的东西应该有一个大于 100 但小于 304 的宽度,并且有默认的 superview 边距。请注意,我不知道上述约束是否真的有意义(例如,它可能总是给你 304 宽度的 subview ,因为这会留下默认边距),但它作为一个例子。

关于ios - 使用 iOS Auto Layout 在 subview Controller 和它的父 View 之间建立约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13200525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com