在集合视图中设置背景颜色时,使用点语法与方括号

时间:2013-05-15 21:47:13

标签: ios objective-c ios6

我还在学习IOS SDK,所以希望这是有道理的。我仍然试图用点语法来解决问题。有人可以解释为什么这个代码不起作用,但第二个代码呢?

不工作:

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionView *cell = [collectionView cellForItemAtIndexPath:indexPath];
    [[cell contentView] setBackgroundColor:[UIColor blueColor]];
}

工作:

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionView *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor blueColor];
}

我只是不明白为什么第一个代码不能正常工作。我正在使用最新版本的Xcode。是否将setBackgroundColor方法弃用为其他内容?

1 个答案:

答案 0 :(得分:1)

使用点表示法时,请务必记住需要以任何方式更改属性名称。所以如果你说:

@property (nonatomic) NSString *message;

编译器会为您处理settergetter方法,因此在此属性上使用点表示法所需要做的就是:

self.message;         // getter
self.message = @"hi"; // setter
// the only difference being - which side of the = sign is your property at

另一方面,如果您想要更改setter / getter的行为,那么然后必须以下列方式定义setMessage方法,以实现(而不是覆盖) )你自己的setter

- (void)setMessage:(NSString *)message {
    // custom code...
    _message = message;
}

也许这就是你困惑的事情。至于setBackgroundColor,它仍然存在,你只是不使用点符号来访问它,顺便提一下,它允许各种各样的整洁的东西:

// .h
@property (nonatomic) int someNumber;

// .m
self.someNumber = 5;   // calls the setter, sets property to 5
self.someNumber += 10; // calls the setter and getter, sets property to 15
self.someNumber++;     // calls the setter and getter, sets property to 16
相关问题