iOS视觉格式语言

Haa*_*nti 3 objective-c ios

我正在尝试通过代码构建一个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;
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse constraint format:  dateNumberView is not a key in the views dictionary. |-[dateNumberView]-| 
Run Code Online (Sandbox Code Playgroud)

怎么了?

Wai*_*ain 7

不要使用:

NSDictionary *views = NSDictionaryOfVariableBindings(self.dateNumberView);
Run Code Online (Sandbox Code Playgroud)

因为该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;
}
Run Code Online (Sandbox Code Playgroud)


Abi*_*ern 7

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

试试这个:

NSDictionary *views = NSDictionaryOfVariableBindings(_dateNumberView);
Run Code Online (Sandbox Code Playgroud)

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

  • 您的回答是有道理的,然而,在Apple的文档中以这种方式创建约束.https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/AutoLayoutinCode/AutoLayoutinCode.html这是一个错误吗? (2认同)