iOS DeveloperiOS学习笔记

UICollection代理方法didSelectItemAtI

2016-10-17  本文已影响3428人  追风筝的boy

需求:

问题:

原因

解决方法分析

You typically do not set the value of this property directly. Changing the value of this property programmatically does not change the appearance of the cell. The preferred way to select the cell and highlight it is to use the selection methods of the collection view object.
这个属性仅仅是用于管理cell的选中状态.默认这个值为NO.意味着cell默认情况下是没有被选中的.
通常情况下,不要直接设置这个属性.使用代码来改变这个值并不会改变cell的外观.选中cell,并让cell显示高亮状态最好的方法就是调用UICollectionView相关selection方法来实现.
```
- 官方也建议我们不要直接来设置,直接设置的话有可能并不会达到你想要的效果.经过我的测试,直接设置确实没有作用.同学们可以自己去试一下
- 第二种: -[UICollectionView selectItemAtIndexPath:animated:scrollPosition:]
- 这个方法可能就是苹果官方建议的通过UICollectionView的对象方法来设置cell的选中状态.
- 还是让我们看看官方的解释

    ```objc
    If the allowsSelection property is NO, calling this method has no effect. If there is an existing selection with a different index path and the allowsMultipleSelection property is NO, calling this method replaces the previous selection.

This method does not cause any selection-related delegate methods to be called.
如果allowsSelection属性为NO, 调用这个方法没有任何效果.
如果有任何另外一个已经被选中cell(官方的说明是另外一个索引, 同一个意思)并且allowsMultipleSelection(允许多项选择)这个属性为NO, 那么调用这个方法会取代那个cell的选中状态.
也就是说当 allowsSelection = YES (默认就是YES), allowsMultipleSelection = NO(这个也是默认设置), 调用这个方法就会取消上一个cell的选中状态,然后让当前的cell选中.
```

- 看完官方的解释,相信大家都明白了,刚好就是我们需要的属性

最终解决方案

{
// 需要配置的代码
[collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
}
```

上一篇 下一篇

猜你喜欢

热点阅读