四锻梳、相關樣式的修改
? ? ? ? 有時我們可能需要調(diào)整 collectionView
單元格尺寸衫画、間距睡榆,或者修改 section
頭尾視圖尺寸等等场航。雖然 RxSwift
沒有封裝相關的方法缠导,但我們?nèi)匀豢梢酝ㄟ^相關的代理方法來設置。
1溉痢,效果圖
(1)不管屏幕尺寸如何僻造,collectionView
每行總是固定顯示 4 個單元格憋他,即單元格的寬度隨屏幕尺寸的變化而變化。
(2)而單元格的高度為寬度的 1.5 倍髓削。
2竹挡,樣例代碼
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
class ViewController: UIViewController {
var collectionView:UICollectionView!
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
//定義布局方式
let flowLayout = UICollectionViewFlowLayout()
//創(chuàng)建集合視圖
self.collectionView = UICollectionView(frame: self.view.frame,
collectionViewLayout: flowLayout)
self.collectionView.backgroundColor = UIColor.white
//創(chuàng)建一個重用的單元格
self.collectionView.register(MyCollectionViewCell.self,
forCellWithReuseIdentifier: "Cell")
self.view.addSubview(self.collectionView!)
//初始化數(shù)據(jù)
let items = Observable.just([
SectionModel(model: "", items: [
"Swift",
"PHP",
"Python",
"Java",
"C++",
"C#"
])
])
//創(chuàng)建數(shù)據(jù)源
let dataSource = RxCollectionViewSectionedReloadDataSource
<SectionModel<String, String>>(
configureCell: { (dataSource, collectionView, indexPath, element) in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell",
for: indexPath) as! MyCollectionViewCell
cell.label.text = "\(element)"
return cell}
)
//綁定單元格數(shù)據(jù)
items
.bind(to: collectionView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
//設置代理
collectionView.rx.setDelegate(self)
.disposed(by: disposeBag)
}
}
//collectionView代理實現(xiàn)
extension ViewController : UICollectionViewDelegateFlowLayout {
//設置單元格尺寸
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.bounds.width
let cellWidth = (width - 30) / 4 //每行顯示4個單元格
return CGSize(width: cellWidth, height: cellWidth * 1.5) //單元格寬度為高度1.5倍
}
}
//自定義單元格
class MyCollectionViewCell: UICollectionViewCell {
var label:UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
//背景設為橙色
self.backgroundColor = UIColor.orange
//創(chuàng)建文本標簽
label = UILabel(frame: frame)
label.textColor = UIColor.white
label.textAlignment = .center
self.contentView.addSubview(label)
}
override func layoutSubviews() {
super.layoutSubviews()
label.frame = bounds
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}