问题
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?
Not working:
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionView *cell = [collectionView cellForItemAtIndexPath:indexPath];
[[cell contentView] setBackgroundColor:[UIColor blueColor]];
}
Working:
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionView *cell = [collectionView cellForItemAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor blueColor];
}
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?
回答1:
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;
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
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;
}
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
来源:https://stackoverflow.com/questions/16575545/dot-syntax-vs-square-brackets-when-setting-background-color-in-collection-view