简体   繁体   中英

How to select CollectionView cell in RxSwift

I need to select the item at specific index in collection view using RxSwift.This method is not working fine.

 collectionView.rx.modelSelected(SearchResult.self).subscribe(onNext:{ menuItem in }).addDisposableTo(disposeBag) 

Can anybody help?

If you want the indexPath of item selected you can use the following :

collectionView
    .rx
    .itemSelected
        .subscribe(onNext:{ indexPath in
            //your code
        }).disposed(by: disposeBag)

and if you want to the model being selected :

collectionView
        .rx
        .modelSelected(SearchResult.self)
        .subscribe(onNext: { (model) in
            //Your code
        }).disposed(by: disposeBag)

And you can combine the above, to get the modelSelected with their indexPath as follow:

  Observable
            .zip(
                collectionView
                    .rx
                    .itemSelected
                ,collectionView
                    .rx
                    .modelSelected(SearchResult.self)
            )
            .bind{ [unowned self] indexPath, model in

            }
            .disposed(by: disposeBag)
    }

Building off of mojtaba al moussawi's answer, I made an extension to make the zipping easy:

extension Reactive where Base: UICollectionView {
    public func modelAndIndexSelected<T>(_ modelType: T.Type) -> ControlEvent<(T, IndexPath)> {
        ControlEvent(events: Observable.zip(
            self.modelSelected(modelType),
            self.itemSelected
        ))
    }
}

Which you would use like:

collectionView
    .rx
    .modelAndIndexSelected(SearchResult.self)
    .subscribe(onNext: { (model, index) in
        //Your code
    }).disposed(by: disposeBag)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM