在UICollectionView中以编程方式select项目
我有一个UICollectionViewController
:
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return [self.pageTastes count]; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { CellTasteCollectionView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; Taste *taste = [self.pageTastes objectAtIndex:indexPath.item]; [[cell imageView] setImage:taste.image]; [cell setObjectId:taste.objectId]; return cell; }
有用。 我有这个viewDidLoad
,允许用户select多个项目:
[self.collectionView setAllowsMultipleSelection:YES];
我想要的是,第一次加载CollectionView,一些项目被选中编程,基于它们在CellTasteCollectionView
objectId
。
以下是我如何做到这一点:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{ Taste *taste = [self.pageTastes objectAtIndex:indexPath.item]; printf("%s\n", [taste.objectId UTF8String]); }
当用户点击项目时会调用它 – 这不是我想要的:我想要在UICollectionView
加载时自动select项目。
我该怎么做呢?
我认为你从UICollectionView类参考中缺less这个方法:
- (void)selectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UICollectionViewScrollPosition)scrollPosition
如果您需要多个select,您可以多次使用此方法。
对于正确的行为,连续调用4个函数:
// Deselect self.collection.deselectItem(at: previousPath, animated: true) self.collectionView(self.collection, didDeselectItemAt: previousPath) // Select self.collection.selectItem(at: path, animated: true, scrollPosition: .centeredVertically) self.collectionView(self.collection, didSelectItemAt: path)
如果以编程方式调用selectItem
则不会调用didSelectItemAt
。 之后你应该手动调用该方法。
self.collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .bottom) self.collectionView(self.collectionView, didSelectItemAt: IndexPath(item: 0, section: 0))
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; [self.districtTableview selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop]; [self tableView:weakSelf.districtTableview didSelectRowAtIndexPath:indexPath];
我在tableview中使用了上面的方法,它工作。