我不知道为什么我的编程创建的约束是模棱两可的,我什至尝试从具有相同约束的笔尖启动,它有效,但为什么我的代码却没有。
@interface rootViewController: UIViewController
@end
@implementation rootViewController
- (void)loadView
{
self.view = [[UIView alloc] init];
UIView *theView = [[UIView alloc] init];
[self.view addSubview:theView];
NSArray *arr = @[
[theView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
[theView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor],
[theView.centerXAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.centerXAnchor],
[theView.leadingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.leadingAnchor]];
[NSLayoutConstraint activateConstraints:arr];
}
@end
//And I load it in the ApplicationDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window = [[UIWindow alloc] init];
self.window.rootViewController = [[rootViewController alloc] init];
[self.window makeKeyAndVisible];
return YES;
}
调试时找不到问题真的很有趣。
调试输出
感谢Yun Chen的帮助,他告诉我很多,但真正的问题是。
在编程中创建的视图和从接口构建器创建的视图之间有一些不同的东西。
@property(nonatomic) BOOL translatesAutoresizingMaskIntoConstraints;
//the property of UIView
iet读取列表:
默认情况下,属性设置为"是",对于您可以编程的任何视图创建。如果在接口构建器中添加视图,则系统会自动将此属性设置为no。
就是这样,只需将这个隐藏的老板设置为否。一切都起作用。
是的,计算宽度的模棱两可。它不能由Leading
和CenterX
约束来计算。(高度通过顶部和底部约束计算得很好)。所以:
情况1,如果视图的宽度等于其超级视图的,则应删除CenterX
约束,并添加Trailing
约束。
案例2,如果视图的宽度为某个值,并且视图为中心,则应删除Leading
约束,并添加Width
约束。
案例3,如果视图的宽度为一个特定值,并且将视图对齐,则应删除CenterX
约束,并添加Width
约束。