RxDelegateCells 0.1.0

RxDelegateCells 0.1.0

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Sep 2016
SPMSupports SPM

Maintained by Suyeol Jeon.


Downloads

Total9
Week0
Month0

Installs

Apps5
powered by Segment

GitHub

Stars15
Watchers2
Forks2
Issues0
Contributors1
Pull Requests1

Code

Files1
LOCLines of Code 44


 
Depends on:
RxCocoa~> 2.5
RxSwift~> 2.5
 

  • By
  • Suyeol Jeon

RxDelegateCells

UITableView Cell Height and UICollectionView Cell Size for RxSwift.

Why

If you’re using RxSwift with UITableView or UICollectionView, it is difficult to calculate the cell sizes with Observables. Because UITableView requires cell height synchronously, but Observables emit values asynchronously.

For example, assume that we are using MVVM pattern and we have a ViewModel which exposes a message with Driver. We need an actual message value as a String to calculate the cell height. However, since message emits values asynchronously, we cannot access the actual value synchronously.

struct MyCellModel {
    let message: Driver<String>
}

func tableView(tableView: UITableView, heightForRowAtIndexPath: NSIndexPath) -> CGFloat {
    let cellViewModel = self.dataSource.itemAtIndexPath(indexPath)

    cellModel.message // (1) This is `Driver<String>`
        .map { message -> CGFloat in
            let size = CGSize(width: tableView.width - 20, height: .max)
            let options: NSStringDrawingOptions = [.UsesLineFragmentOrigin, .UsesFontLeading]
            let attributes = [NSFontAttributeName: MyCell.Font.messageLabel]
            let rect = message.boundingRectWithSize(size, options: options, attributes: attributes, context: nil)
            return ceil(rect.height) + 20 // (2) We want return this value (async)
        }

    return 40 // (3) But we have to return actual value here, synchronously :(
}

At a Glance

RxDelegateCells makes it available to use Driver<CGFloat> as a UITableView cell height and Driver<CGSize> as a UICollectionView cell size.

This code makes the cell heights 40, 80 and 120.

Driver.just([[.just(40), .just(80), .just(120)]])
    .drive(self.tableView.rx_cellHeightWithDelegate(delegate))
    .addDisposableTo(self.disposeBag)

rxdelegatecells

You can find a real-world example at here.

Installation

  • For iOS 8+ projects with CocoaPods:

    pod 'RxDelegateCells', '~> 0.1'
  • For iOS 8+ projects with Carthage:

    github "devxoul/RxDelegateCells" ~> 0.1
    
  • For iOS 7 projects with CocoaSeeds:

    github 'devxoul/RxDelegateCells', '0.1.0', :files => 'Sources/**/*.swift'
  • Using Swift Package Manager:

    import PackageDescription
    
    let package = Package(
        name: "MyAwesomeApp",
        dependencies: [
            .Package(url: "https://github.com/devxoul/RxDelegateCells", "0.1.0"),
        ]
    )

License

RxDelegateCells is under MIT license. See the LICENSE file for more info.