1

我认为一个非常简单的问题:

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 时,它的约束已经相对于控制器设置。

我试过了,没有崩溃,但UIViewx 和 y 坐标变得很奇怪

也许我需要更新约束?或者这根本不可能?

4

3 回答 3

3

我不确定您到底在寻找什么 ui 行为,因为您似乎正试图将视图的前导空间与其父视图的前导空间联系起来。作为前导空间,视图左侧的空间,您是否正在寻找更常见的“将我的左侧从我父母的左边界粘贴 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

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

于 2013-09-08T00:50:25.683 回答
1

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

在一个方向上,您至少需要

一条边和宽度(或高度)或两条边(隐式宽度或高度)或基于水平(或垂直)中心的约束和显式宽度(或高度分别)

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

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

于 2013-09-08T01:00:39.280 回答
0

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

于 2015-04-17T22:52:50.090 回答