2016-12-17 2 views
0

Hier Sammlung Ansicht 3 Spalten in 1 Reihe zeigen, ist mein Code:Wie mit RxSwift

import UIKit 
import RxSwift 
import RxCocoa 
import RxOptional 

class ViewController: UIViewController { 

    @IBOutlet weak var collectionView: UICollectionView! 

    let disposeBag = DisposeBag() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view. 

     let items = Observable.just(
      (0..<20).map{ "Test \($0)" } 
     ) 

     items.asObservable().bindTo(self.collectionView.rx.items(cellIdentifier: CustomCollectionViewCell.reuseIdentifier, cellType: CustomCollectionViewCell.self)) { row, data, cell in 
      cell.data = data 
      }.addDisposableTo(disposeBag) 
    } 
} 

enter image description here

So wie 3 Spalten in 1 Zeile zu zeigen.

Ich kann kein Tutorial über Sammelansicht mit RxSwift finden.

+0

Try Breite von CollectionViewCell – guru

+0

Hallo @guru zu erhöhen, wissen Sie, wie es im Code zu tun? – Khuong

+0

func Kollektion (_ Collection: UICollectionView, Layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize (Breite: yourWidth, Höhe: yourHeight) } – guru

Antwort

9

Etwas wie folgt aus:

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout { 

    .... 

    override func viewDidLoad() { 
     super.viewDidLoad() 

      ... 

     items.asObservable().bindTo(self.collectionView.rx.items(cellIdentifier: CustomCollectionViewCell.reuseIdentifier, cellType: CustomCollectionViewCell.self)) { row, data, cell in 
      cell.data = data 
     }.addDisposableTo(disposeBag) 

     // add this line you can provide the cell size from delegate method 
     collectionView.rx.setDelegate(self).addDisposableTo(disposeBag) 
    } 

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
     let width = collectionView.bounds.width 
     let cellWidth = (width - 30)/3 // compute your cell width 
     return CGSize(width: cellWidth, height: cellWidth/0.6) 
    } 
} 
+0

Hi @beethOven, 'collectionView.rx.setDelegate (self) .addDisposableTo (disposeBag)' kann 'self' hier nicht übergeben. – Khuong

+0

Ich muss hinzufügen 'Klasse SecondViewController: UIViewController, UICollectionViewDelegateFlowLayout', es funktioniert. Danke – Khuong

+0

Gern geschehen! Ich habe vergessen, 'UICollectionViewDelegateFlowLayout' hinzuzufügen. – beeth0ven

1

Eine weitere Alternative:

let flowLayout = UICollectionViewFlowLayout() 
let size = (collectionView.frame.size.width - CGFloat(30))/CGFloat(3) 
flowLayout.itemSize = CGSize(width: size, height: size) 
collectionView.setCollectionViewLayout(flowLayout, animated: true)