zgj*_*jie 13 xcode ios uicollectionview uicollectionviewcell
我试着写
[self collectionView:myCollectionView didSelectItemAtIndexPath:selectedIndexPath]
和viewDidLoad中的UICollectionViewCell选择= YES,它确实实现了该方法didSelectItemAtIndexPath
,但未选择单元格.
我在UICollectionViewCell子类中编写了所选状态(void)setSelected:(BOOL)selected
.加载视图后,手动选择功能起作用.但是在视图首次加载后我无法自动选择一些项目.
我试着写代码:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
和
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
,一切都不行.
我发现它第一次运行viewDidLoad
和didSelectItemAtIndexPath
,然后cellForItemAtIndexPath
,好像,我无法让细胞在indexPath
(我知道)之前cellForItemAtIndexPath
,因为在此之前,该小区是不存在的.那么如何在UICollectionView
首次加载后选择一些项?
抱歉我的英语不好.提前致谢.
SAE*_*SAE 11
不确定,如果你的问题是正确的,但这是一个可能的解决方案:
在例如viewWillAppear:
做
[self.collectionView reloadData];
NSIndexPath *selection = [NSIndexPath indexPathForItem:THE_ITEM_TO_SELECT
inSection:THE_SECTION];
[self.collectionView selectItemAtIndexPath:selection
animated:YES
scrollPosition:UICollectionViewScrollPositionNone];
Run Code Online (Sandbox Code Playgroud)
请记住,以编程方式调用'selectItemAtIndexPath'不会调用相关的委托方法; 如果需要,你必须在代码中调用它们.
在我的情况下selectItemAtIndexPath
没有影响reloadData
,所以我不得不在完成块中调用它performBatchUpdates
:
collectionView.dataSource = ...
collectionView.delegate = ...
let indexPath = ...
collectionView.performBatchUpdates(nil) { _ in
collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: .None)
}
Run Code Online (Sandbox Code Playgroud)
小智 7
斯威夫特 3
在创建 collectionview 的位置实现此覆盖函数。假设我们有 1 个第 1 行,如 Instagram 故事。
override func viewDidAppear(_ animated: Bool) {
// Auto Select First Item
self.myCollectionView.performBatchUpdates(nil) { _ in
self.myCollectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: false, scrollPosition: [.centeredHorizontally])
self.collectionView(self.myCollectionView, didSelectItemAt : IndexPath(item: 0, section: 0))
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21102 次 |
最近记录: |