微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐