Select items programmatically in UICollectionView

后端 未结 4 972
小鲜肉
小鲜肉 2020-12-09 17:27

I have a UICollectionViewController:

- (NSInteger)collectionView:(UICollectionView *)collectionView 
     numberOfItemsInSection:(NSInteger)sect         


        
相关标签:
4条回答
  • 2020-12-09 17:49
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.districtTableview selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
    [self tableView:weakSelf.districtTableview didSelectRowAtIndexPath:indexPath];
    

    I used the above method in tableview, and it worked.

    0 讨论(0)
  • 2020-12-09 17:54

    I think you are missing this method from the UICollectionView Class Reference:

    - (void)selectItemAtIndexPath:(NSIndexPath *)indexPath 
                         animated:(BOOL)animated 
                   scrollPosition:(UICollectionViewScrollPosition)scrollPosition
    

    You can use this method multiple times if you want multiple selections.

    0 讨论(0)
  • 2020-12-09 17:54

    didSelectItemAt is not called if you call selectItem programmatically. You should call the method manually after it.

    self.collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .bottom)
    self.collectionView(self.collectionView, didSelectItemAt: IndexPath(item: 0, section: 0))
    
    0 讨论(0)
  • 2020-12-09 18:14

    For right behaviour call 4 function in a row:

    // 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)
    
    0 讨论(0)
提交回复
热议问题