2016-12-17 70 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)