ios – 以编程方式设置约束与IB中的设置不同?

我是iOS中的新版Auto Layout.我原则上很喜欢这个概念,但是它驱使我坚持尝试让最简单的事情完成.我怀疑我仍然缺少一些简单的基本原则.我正在尝试通过在应用程序中实际使用它之前在基础知识中获得基础知识,因此我正在创建非常简单的测试项目.这是一个简单的,因为它不能按预期工作.首先是工作的部分.在IB中,我添加一个视图来填充整个viewcontroller,并且XCode自动将约束条件设置为Top / Bottom / Leading / Trailing,并将空格设置为0.当完成IB时,它的工作原理如下:

旋转到

大!

现在我试图在代码中做同样的事情:

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view,typically from a nib.
UIView *redView = [[UIView alloc] initWithFrame:self.view.bounds];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];

redView.translatesAutoresizingMaskIntoConstraints = NO;

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0f constant:0.0f]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.0f]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0f constant:0.0f]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributetop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.0f]];
}

这就是除了单视图应用程序的代码之外的所有代码.

当我运行上面的代码,尝试镜像同样的事情,我以IB编程方式,我得到这个旋转后:

同样的限制如何导致不同的结果?这可能是一件非常简单和尴尬的事情,我失踪了.帮帮我!!!

解决方法

我将如何做到这一点:
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[redView]|"
                                                                  options:0
                                                                  metrics:nil
                                                                    views:NSDictionaryOfVariableBindings(redView)]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[redView]|"
                                                                  options:0
                                                                  metrics:nil
                                                                    views:NSDictionaryOfVariableBindings(redView)]];

IB中的AutoLayout可能是一种痛苦,我发现熟悉Visual Format语言的功能比constraintWithItem更少:attribute:relatedBy:toItem:attribute:multiplier:constant:

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...