iOS视觉格式语言

时间:2013-11-06 15:20:23

标签: ios objective-c

我正在尝试通过代码构建一个View。在我的初学者中我有这个:

- (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 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:7)

使用self.只是用于调用返回对象的方法的语法糖,它不是可以用作键的东西。

请改为尝试:

NSDictionary *views = NSDictionaryOfVariableBindings(_dateNumberView);

如果您使用自动合成属性,那么哪个应该是正确的。

答案 2 :(得分:0)

我认为您正在尝试对@property变量使用视觉格式 因此,请检查以下链接,它可能会对您有帮助

Layout: How to use property in visual format