我可以在自定义视图中直接将约束设置为superview吗?

时间:2013-09-07 23:27:28

标签: ios objective-c constraints autolayout

我估计一个非常简单的问题:

一个UIViewController

一个自定义UIView

控制器只执行:

-(void)loadView{
   [super loadView];
   self.sideMenu = [[sideMenuView alloc]init];
   [self.view addSubview:self.sideMenu];
}

UIView我想做的事情如下:

      self.translatesAutoresizingMaskIntoConstraints = NO;

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.superview attribute:NSLayoutAttributeLeading multiplier:1 constant:100];
[self.superview addConstraint:constraint];

因此,当我在控制器中创建UIView时,其约束已经相对于控制器设置。

我已经尝试过,没有任何崩溃,但UIView真的很奇怪x和y coords

Maby我需要更新约束吗?或maby这根本不可能?

3 个答案:

答案 0 :(得分:3)

我不确定你正在寻找什么样的行为,因为看起来你正试图将视图的前导空间与其超视图的前导空间联系起来。作为领先的空间,视图左侧的空间,可能是你正在寻找更常见的“从我父母的左边缘贴上我的左侧100像素”?无论如何,在任何一种情况下,我都会将控制器的插座连接到自定义视图(即下面的myCustomView),然后通过覆盖在UIViewController而不是UIView中构建约束:

- (void)updateViewConstraints {
    [super updateViewConstraints];
    NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:myCustomView
                                                                  attribute:NSLayoutAttributeLeading
                                                                  relatedBy:NSLayoutRelationEqual
                                                                     toItem:myCustomView.superview
                                                                  attribute:NSLayoutAttributeLeading
                                                                 multiplier:1
                                                                   constant:100];
    [myCustomView addConstraint:constraint];
}

Apple有一个有趣的页面,其中包含一个表格,显示此地址自动布局的各种运行时入口点: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/Articles/runtime.html#//apple_ref/doc/uid/TP40010853-CH6-SW1

您也可以考虑添加其他约束。自动布局倾向于以最糟糕的方式利用您未经检查的任何自由; - )

答案 1 :(得分:1)

所以领先优势还不够。 您需要足够的约束来满足垂直和水平布局。

在一个方向,你至少需要

一个边缘&宽度(或高) 要么 两条边(隐式宽度或高度) 要么 基于水平(或垂直)中心的约束和显式宽度(或高度)

关于宽度和高度的事情是它们也可以由内在的内容大小来确定。

将视图添加到superview后添加约束。

答案 2 :(得分:0)

有点晚了,但PureLayout非常方便https://github.com/smileyborg/PureLayout

相关问题