iOS 可视化格式语言

3

我正在尝试通过代码构建一个视图。在我的init函数中,我有以下代码:

- (id) init{
    self = [super init];
    if(self){
       [self setFrame:CGRectMake(0, 0, 0, 50)];   
       [self addSubview:[self dateNumberView]];
        NSDictionary *views = NSDictionaryOfVariableBindings(self.dateNumberView);
       [self.dateNumberView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-[dateNumberView]-|" options:0 metrics:nil views:views]];
    }
    return self;
}

我收到的错误消息是:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse constraint format:  dateNumberView is not a key in the views dictionary. |-[dateNumberView]-| 

有什么问题吗?

3个回答

7

不要使用:

NSDictionary *views = NSDictionaryOfVariableBindings(self.dateNumberView);

因为系统会误解self.部分(KVC类型导航),所以应该获取视图的本地引用并在整个代码中使用它:

- (id) init{
    self = [super init];
    if(self) {
       UIView *dateNumberView = [self dateNumberView];

       [self setFrame:CGRectMake(0, 0, 0, 50)];   
       [self addSubview: dateNumberView];
        NSDictionary *views = NSDictionaryOfVariableBindings(dateNumberView);
       [dateNumberView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-[dateNumberView]-|" options:0 metrics:nil views:views]];
    }

    return self;
}

7
使用self.只是调用返回对象的方法的语法糖,它不能作为键使用。请尝试使用以下代码替代:
NSDictionary *views = NSDictionaryOfVariableBindings(_dateNumberView);

如果您正在使用自动合成的属性,则应该是正确的。

2
你的回答很有道理,但是这种方式在苹果的文档中是被创建为约束条件的。https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/AutoLayoutinCode/AutoLayoutinCode.html 这是一个错误吗? - Anthony Mattox
@AnthonyMattox 看起来出现了一个错误。苹果的示例代码对我来说无效。 - Sami Samhuri

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接