2016-12-17 73 views
0

這裏是我的代碼:如何顯示集合視圖爲1行3列與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

所以如何顯示1行3列。

我找不到任何有關RxSwift集合視圖的教程。

+0

嘗試增加CollectionViewCell – guru

+0

嗨@guru的寬度,你知道如何做到這一點的代碼? – Khuong

+0

FUNC的CollectionView(_的CollectionView:UICollectionView,佈局collectionViewLayout:UICollectionViewLayout,sizeForItemAt indexPath:IndexPath) - > CGSize { 回報CGSize(寬度:yourWidth,高度:yourHeight) } – guru

回答

9

事情是這樣的:

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

嗨@beethOven,'collectionView.rx.setDelegate(self).addDisposableTo(disposeBag)''無法在這裏傳遞'self'。 – Khuong

+0

我需要添加'類SecondViewController:UIViewController,UICollectionViewDelegateFlowLayout',它的工作原理。謝謝 – Khuong

+0

不客氣!我忘了添加'UICollectionViewDelegateFlowLayout'。 – beeth0ven

1

另一種選擇:

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)