2014-10-06 58 views
0

我一直想弄清楚如何使用NSLayoutConstraint的constraintWithItem方法创建一个NSLayoutConstraint对象,该方法与下面的代码等效。如何在代码中创建与@“H:| -10- [view]”完全相同的NSLayoutConstraint对象?

NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:"@H:|-10-[view]" 
                   options:0 
                   metrics:nil 
                   views:NSDictionaryOfVariableBindings(view)]; 

NSLayoutConstraint *rightMarginConstraint = [constraints firstObject]; 

我已经试过代码如下图所示:

NSLayoutConstraint* rightMarginConstraints = [NSLayoutConstraint constraintWithItem:view 
                attribute:NSLayoutAttributeLeading 
                relatedBy:NSLayoutRelationEqual 
                 toItem:superview 
                attribute:NSLayoutAttributeLeft 
                multiplier:1.0f 
                 constant:10.0f]; 

但它不会做了很多同样的事情,它是在控制台上不同的,当它打印出来。我想在控制台上输出一个约为"H:|-10-[view]"的约束。

有谁知道如何创建一个iOS7和8的作品? (我发现有iOS 8的新属性选项,但我仍然支持iOS 7)

在此先感谢!

/////////编辑////////

实际产生的完全相同的约束上简单视图&上海华的代码的第二块。 然而,我在上TableViewCells问题,我得到如下结果:

这是我想要的,与代码生成类似的代码

<NSLayoutConstraint:0x7fc050f481c0 H:|-(10)-[UIView:0x7fc050f48070] (Names:     '|':UITableViewCellContentView:0x7fc050f39310)> 

的第二块的第一块代码产生约束类似以下的输出

<NSLayoutConstraint:0x7b6513d0 view:0x7b64cdf0.leading == UITableViewCellContentView:0x7b64cd10.left> 

///编辑2 /// 我也越来越输出看起来甚至低于我用匹配的属性代码。

<NSLayoutConstraint:0x7d695c70 CustomBorderView:0x7d4cb0f0.right == UITableViewCellContentView:0x7d4cb010.right + 10> 

///编辑3 ///

我想通了项目事项的顺序。我交换了constraintWithItem的参数:toItem:现在输出我想要的东西。谢谢!

+0

它是做什么的,它打印到控制台是什么? – rdelmar 2014-10-06 21:19:07

+0

向我们展示两者的打印日志。 – Tricertops 2014-10-06 21:19:56

回答

3

NSLayoutAttributeLeftNSLayoutAttributeLeading不一样。试试这个:

NSLayoutConstraint* rightMarginConstraints = [NSLayoutConstraint 
    constraintWithItem:view attribute:NSLayoutAttributeLeading 
    relatedBy:NSLayoutRelationEqual 
    toItem:superview attribute:NSLayoutAttributeLeading 
    multiplier:1.0f constant:10.0f]; 

或本:

NSLayoutConstraint* rightMarginConstraints = [NSLayoutConstraint 
    constraintWithItem:view attribute:NSLayoutAttributeLeft 
    relatedBy:NSLayoutRelationEqual 
    toItem:superview attribute:NSLayoutAttributeLeft 
    multiplier:1.0f constant:10.0f]; 

这两个给我你所需的输出。混合...Left...Leading给我你不想要的输出。

+0

我已经尝试了两种方法,他们给了我相同的结果。对我来说,左派应该是绝对的,领导应该是相对的,但我无法真正地发现他们两人的差异。有人可以解释什么时候以及如何使用Leading和Left不同吗? – 2015-06-29 14:21:42

相关问题