Коллекция ViewCells с собственным размером с использованием RxDataSource

Как добиться собственного размера collectionViewCells с помощью RxDataSource?

я пытался установить

flowLayout.estimatedItemSize = CGSize(width: 187, height: 102)

Но затем приложение вылетает при изменении dataSourceObservable.

Я пытался установить размер ячейки внутри

dataSource.configureCell = { [weak self] (dataSource, collectionView, indexPath, _) in 

Это не очень хорошая идея, потому что ячейки перекрываются, и это потому, что я не использую

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize

Теперь возможно ли правильно расположить размеры ячеек, используя только наблюдаемые? Это не называть что-то вроде

dataSourceVar.value[indexPath].cellSize

Внутри collectionView sizeForItemAt?


person Xernox    schedule 03.03.2017    source источник


Ответы (1)


Добавить представление коллекции в раскадровку. Импортируйте RxDataSources как зависимость.

import UIKit
import RxSwift
import RxCocoa
import RxDataSources

class ViewController: UIViewController {

  private let disposeBag = DisposeBag()
  
  @IBOutlet weak var collectionView: UICollectionView!
  @IBOutlet weak var collectionLayout: UICollectionViewFlowLayout! {
    didSet {
      collectionLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
    }
  }
  
  private let section = BehaviorRelay(
    value: Section(items: [
      Item(title: "Lorem ipsum dolor sit amet, consectetur"),
      Item(title: "adipiscing elit, sed do eiusmod tempor"),
      Item(title: "incididunt ut labore et dolore magna aliqua"),
      Item(title: "Ut enim ad minim veniam"),
      Item(title: "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
      Item(title: "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
      ]
    )
  )

  private lazy var collectionDatasource = {
    return RxCollectionViewSectionedReloadDataSource<Section>(
      configureCell: { (dataSource, collectionView, indexPath, item) -> UICollectionViewCell in
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionCell
        cell.titleLabel.text = item.title
        cell.layer.borderWidth = 0.5
        cell.layer.borderColor = UIColor.lightGray.cgColor
        cell.maxWidth = collectionView.bounds.width - 16
        return cell
    })
  }()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    initCollection()
  }
  
  private func initCollection() {
    section
      .asObservable()
      .map({ return [$0] })
      .bind(to: collectionView.rx.items(dataSource: collectionDatasource))
      .disposed(by: disposeBag)
  }
}

Модель данных

  import Foundation
  
  struct Item {
    let title: String
  }

Создать подкласс класса SectionModelType

import RxDataSources

  struct Section {
    var items: [Item]
  }
  
  extension Section: SectionModelType {
    
    init(
      original: Section,
      items: [Item]) {
      
      self = original
      self.items = items
    }
  }

Класс ячейки представления коллекции

import UIKit

class CollectionCell: UICollectionViewCell {
  @IBOutlet weak var titleLabel: UILabel!
  
  // Note: must be strong
  @IBOutlet private var maxWidthConstraint: NSLayoutConstraint! {
      didSet {
          maxWidthConstraint.isActive = false
      }
  }
  
  var maxWidth: CGFloat? = nil {
      didSet {
          guard let maxWidth = maxWidth else {
              return
          }
          maxWidthConstraint.isActive = true
          maxWidthConstraint.constant = maxWidth
      }
  }
  
  override func awakeFromNib() {
      super.awakeFromNib()
      
      contentView.translatesAutoresizingMaskIntoConstraints = false
      
      NSLayoutConstraint.activate([
          contentView.leftAnchor.constraint(equalTo: leftAnchor),
          contentView.rightAnchor.constraint(equalTo: rightAnchor),
          contentView.topAnchor.constraint(equalTo: topAnchor),
          contentView.bottomAnchor.constraint(equalTo: bottomAnchor)
          ])
  }
}
person chatterjee86    schedule 03.07.2019