在集合视图中设置背景颜色时,使用点语法与方括号 [英] Dot syntax vs square brackets when setting background color in collection view
问题描述
我还在学习IOS SDK,所以希望这是有道理的。我仍然试图用点语法来解决问题。有人可以解释为什么这个代码不起作用,但第二个代码呢?
I'm still learning IOS SDK so hopefully this makes sense. I am still trying to wrap my head around using dot syntax. Could some one explain why this code doesn't work but the second one does?
不工作:
-(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方法弃用为其他东西?
I just don't understand why the first code won't work as well. I am using the newest version of Xcode. Was the setBackgroundColor method deprecated into something else?
推荐答案
当您使用点符号时,请记住您 don 't 需要以任何方式更改属性名称。所以如果你说:
When you use dot notation, always keep in mind that you don't need to change the property name in any way. So if you say have:
@property (nonatomic) NSString *message;
编译器负责 setter
和 getter
方法,所以你需要做的就是在这个属性上使用点符号:
The compiler takes care of the setter
and getter
methods for you, so all you have to do to use the dot notation on this property is this:
self.message; // getter
self.message = @"hi"; // setter
// the only difference being - which side of the = sign is your property at
另一方面,如果您想要更改setter / getter的行为,那么然后必须定义 setMessage
方法以下方式,实现(不覆盖)您自己的 setter
:
If on the other hand you want to change the behaviour of the setter/getter, you then have to you define the setMessage
method in the following way, to implement (not override) your own setter
:
- (void)setMessage:(NSString *)message {
// custom code...
_message = message;
}
也许这就是你所困惑的。对于 setBackgroundColor
,它仍然存在,你只是不使用点符号访问它,顺便提一下,允许所有种类这样简洁的东西:
Maybe that's what you're confusing. As for setBackgroundColor
, it's still there, you just don't access it using the dot notation, which, by the way, allows for all kinds of neat stuff like this:
// .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
这篇关于在集合视图中设置背景颜色时,使用点语法与方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!