LoginSignup
43
45

More than 5 years have passed since last update.

RxSwiftで簡単にデザインモックを作成する

Posted at

タイムラインのデザインモックをRxSwiftで簡単に作ってみた

Facebook-LikeなタイムラインをRxSwiftを使って作ってみた⇨レポジトリーはここ

Screen Shot 2016-04-11 at 12.21.21 AM.png

structでモデルを作成

Timeline
struct Timeline {
    let name: String
    let profileImage: UIImage
    let bodyContent: String
}

structを使う場面
1. 少ないデータを1つのカプセルとして保有したい時
2. 参照してデータを渡すより、値をコピーして渡したい時
3. 継承する必要がない場合

購読可能な値を作る

viewController
override func viewDidLoad() {
        super.viewDidLoad()

        let elements = Driver.just([
            Timeline(name: "yuzushioh", profileImage: UIImage(named: "")!, bodyContent: ""),
            Timeline(name: "yuzushioh", profileImage: UIImage(named: "")!, bodyContent: ""),
            Timeline(name: "yuzushioh", profileImage: UIImage(named: "")!, bodyContent: ""),
            ....
        ])
}

前回のDriverの記事でも述べたようにObservable.just()の代わりにUIに特化したDriver.justを使います。これで[Timeline]のストリームを作成しました。

TableViewにつなぎこむ

viewController
    override func viewDidLoad() {
        super.viewDidLoad()

        let elements = Driver.just([
             ....
        ])

        elements.asDriver()
            .drive(tableView.rx_itemsWithCellIdentifier("Cell", cellType: TableViewCell.self)) { _, timeline, cell in
                cell.timeline = timeline
            }
            .addDisposableTo(disposeBag)
    }

Drive.justで作ったストリームをUIに特化されているDriveを使ってtableViewにバインドします!

tableView
       .drive(tableView.rx_itemsWithCellIdentifier("Cell", cellType: TableViewCell.self)) { _, timeline, cell in
                cell.timeline = timeline
            }

上記のコードで

tableView
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell

        ...

        return cell
    }

と同じ事ができるだけでなくitemの数をなどを自動で反映してくれるのでとても便利です!

完成

今回はモックのデータをDriver.just()で作成してそれをtableViewDriveしてタイムラインを実装するところまでしか行っていませんがRxには以下のようにtapしたrowのmodelを取得するメソッドも用意されているので画面遷移も簡単に作成できます!

tableView
tableView.rx_modelSelected(Timeline)
            .subscribeNext { timeline in
                ...
            }
            .addDisposableTo(disposeBag)
43
45
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
43
45