Objective C相当于Swift addConstraints?

时间:2017-08-29 16:57:05

标签: ios objective-c ios-autolayout

我是使用代码自动布局的新手。

addConstaints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-16-[v0]-16-|",options:NSLayoutFormatOptions(), metrics:nil ,views:["v0":thumbnailImageView]))

addConstaints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-16-[v0]-16-|",options:NSLayoutFormatOptions(), metrics:nil ,views:["v0":thumbnailImageView]))

Iam尝试使用下面的代码在Objective C中实现上面的swift代码但是app在加载时崩溃并且出现以下错误

由于未捕获的异常终止应用' NSInvalidArgumentException',原因:'无法解析约束格式: 期待一个观点 H:| -16- [v0] -16- |   ^'

    [self addConstraints:[NSLayoutConstraint 
constraintsWithVisualFormat:@"H:|-16-[v0]-16-|" 
options:0 
metrics:nil 
views:NSDictionaryOfVariableBindings(thumbnailImageView)]];

    [self addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"V:|-16-[v0]-16-|" 
options:0 
metrics:nil 
views:NSDictionaryOfVariableBindings(thumbnailImageView)]];

.....

UIImageView * thumbnailImageView = [[UIImageView alloc] init];
        thumbnailImageView.backgroundColor = [UIColor greenColor];
        thumbnailImageView.translatesAutoresizingMaskIntoConstraints = false;

        [self addSubview:thumbnailImageView];


        thumbnailImageView.frame = CGRectMake(0, 0, 100, 100);

2 个答案:

答案 0 :(得分:3)

NSDictionaryOfVariableBindings生成与Objective-C变量名匹配的变量绑定。所以你需要把约束写为

[self addConstraints:[NSLayoutConstraint 
constraintsWithVisualFormat:@"H:|-16-[thumbnailImageView]-16-|" 
options:0 
metrics:nil 
views:NSDictionaryOfVariableBindings(thumbnailImageView)]];

或者您只需跳过NSDictionaryOfVairableDBindings并使用:

[self addConstraints:[NSLayoutConstraint 
constraintsWithVisualFormat:@"H:|-16-[v0]-16-|" 
options:0 
metrics:nil 
views:@{ @"v0" : thumbnailImageView } ];

这有点像Swift版本。 (目前没有编译器方便,所以第二部分可能会出现一些小的语法错误。请尽快检查。)

答案 1 :(得分:3)

您错误地使用了需要传递变量名称的宏NSDictionaryOfVariableBindings

  

/ *这个宏是用于制作视图词典的助手   + constraintsWithVisualFormat:选择:指标:观点:。 NSDictionaryOfVariableBindings(v1,v2,v3)相当于   [NSDictionary dictionaryWithObjectsAndKeys:v1,@“v1”,v2,@“v2”,v3,   @“v3”,nil]; * /

 [self addConstraints:[NSLayoutConstraint 
constraintsWithVisualFormat:@"H:|-16-[thumbnailImageView]-16-|" 
options:0 
metrics:nil 
views:NSDictionaryOfVariableBindings(thumbnailImageView)]];

    [self addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"V:|-16-[thumbnailImageView]-16-|" 
options:0 
metrics:nil 
views:NSDictionaryOfVariableBindings(thumbnailImageView)]];