您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

用 RxSwift 實作一個 UITableView(含踩坑記錄)

編輯:iOS 開發基礎

本文為投稿文章,作者:馬克叔_Marco(簡書)

前言

因為和同事臨時決定要在專案裡導入 MVVM 架構 + 響應式編程 + Swift,最近一直在啃 RxSwift。由於中文教程和文件還不完善,學習過程踩了很多坑——比如一個看似簡單的 UITableView 就折騰了好久。

於是決定把自己遇到的坑記錄下來,順便翻譯一些有用的英文材料,給後來的踩坑者留點經驗。

今天要介紹的是 UITableView 在 RxSwift 中的用法。我搜了不少資料,最後找到〈Implement a UITableView in RxSwift〉這篇博文,照著上面的例子把 UITableView 實作出來了。今天的內容主要翻譯這篇博文,加上我自己的一些改良。

RxSwift 是什麼

RxSwift 是針對 Swift 語言的響應式編程框架,目標是讓異步操作與事件/資料流的實作變得簡單。這裡不展開介紹,直接進主題。

動手做

用 Xcode 新建一個專案,語言選 Swift,然後把 RxSwift 引入。你可以用 CocoaPods 管理三方庫,Podfile 長這樣:

source 'https://github.com/CocoaPods/Specs.git'

platform :ios, '8.1'

use_frameworks!

target 'RxTableView' do
  pod 'RxSwift'
  pod 'RxCocoa'
end

注意!一定要裝 RxDataSources 這個三方庫!

RxDataSources 用 RxSwift 對 UITableView 與 UICollectionView 的資料源做了一層包裝。我最初嘗試時沒有引入它,結果一啟動就 Crash,一啟動就 Crash,無限循環。最麻煩的是官方範例並沒有在 Podfile 裡加入這個庫,而是直接手動放進專案,沒仔細看目錄結構根本不會發現還有這東西。所以你的 Podfile 應該長這樣:

source 'https://github.com/CocoaPods/Specs.git'

platform :ios, '8.1'

use_frameworks!

target 'RxTableView' do
  pod 'RxSwift'
  pod 'RxCocoa'
  pod 'RxDataSources'
end

接著新建一個 ViewController,加上一個 UITableView:

import UIKit
import RxCocoa
import RxSwift
import RxDataSources

class RxTableViewController: UIViewController {

    let tableView: UITableView = UITableView(frame: UIScreen.mainScreen().bounds, style: .Plain)

    let reuseIdentifier = "\(TableViewCell.self)"

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(tableView)
        tableView.registerClass(TableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
    }
}

很好,現在是不是該實作 UITableViewDelegate 和 UITableViewDataSource 了?

其實不需要。既然用了響應式編程,就不用再寫那些資料源與代理方法了。你只要確保控制器裡 import 了 RxSwift 和 RxDataSources 兩個模組,接下來用 RxSwift 來配置 TableView 即可。

細心的你可能注意到我自訂了一個 TableViewCell,後面再提。

現在建立一個 Model 來代表簡書的用戶物件,它有三個屬性:關注數、粉絲數、暱稱。

import Foundation

struct User {
    let followersCount: Int
    let followingCount: Int
    let screenName: String
}

你可能會疑惑:為什麼 Model 用 Struct 而不是 Class?

我也一樣疑惑。我翻譯的這篇博文的原作者就是這樣寫的,而且他建立的 ViewModel 檔還 import 了 UIKit——實際上 MVVM 模式下 ViewModel 最好不要包含 UI 相關元素。不過先別計較這些細節,畢竟我們這篇的目的是研究 UITableView 的用法。

回到 ViewController,宣告這樣一個屬性:

let dataSource = RxTableViewSectionedReloadDataSource()

RxDataSources 用它來指定資料源的內容:SectionModel 帶一個 String 作為 section 名稱,User 作為 item 型別。如果你看不太懂,可以按住並點擊這個宣告,檢視它內部的實作。

接著建立一個 ViewModel 類來傳遞資料源。為了達到解耦的目的,要避免直接在控制器裡處理 Model。你的 ViewModel 長這樣:

import Foundation
import RxSwift
import RxDataSources

class ViewModel: NSObject {
}

為 ViewModel 加上一個取資料的功能。真實應用中,資料通常是透過網路請求解析 JSON 得到的;在這個範例裡,我們先寫一段假資料。

import Foundation
import RxSwift
import RxDataSources

class ViewModel: NSObject {

    func getUsers() -> Observable {

        return Observable.create { (observer) -> Disposable in

            let users = [
                User(followersCount: 19_901_990, followingCount: 1990,  screenName: "Marco Sun"),
                User(followersCount: 19_890_000, followingCount: 1989,  screenName: "Taylor Swift"),
                User(followersCount: 250_000,    followingCount: 25,    screenName: "Rihanna"),
                User(followersCount: 13_000_000_000, followingCount: 13, screenName: "Jolin Tsai"),
                User(followersCount: 25_000_000, followingCount: 25,    screenName: "Adele")
            ]

            let section = [SectionModel(model: "", items: users)]

            observer.onNext(section)
            observer.onCompleted()

            return AnonymousDisposable {}
        }
    }
}

Observable 是響應式編程裡最重要也最基本的概念,它是一串序列化的值。這也是為什麼用它來做異步取資料這麼方便的原因——你可以串接多個 Observable,等它們全部完成後再刷新資料(看不懂這段的人建議回去補一下 RxSwift 的幾個基礎概念)。

我們剛定義的 Observable,內容是一個裝著 SectionModel 的陣列,每個 SectionModel 包含 String 型別的標題與 User 型別的 item。它就是我們 TableView 每一 row 資料的容器。這裡塞了五筆假資料並建立一個 section,section 名稱用了空字串——如果你想給 section 的區頭加上 title,可以填入字串並在控制器裡實作 titleForHeaderInSection。

之後透過 onCompleted() 告訴 Observable 序列已經結束。回傳 AnonymousDisposable() 確保函式返回後資源能被釋放與清理;如果你用了網路請求,可以在這個閉包裡取消所有尚未完成的請求。關於事件序列與 Disposable,Getting Started 指南有更好的解釋。

ViewModel 的邏輯寫完,回到控制器把資料源串起來。先建立 DisposeBag,它負責在控制器銷毀後控制資源釋放。

let dataSource = RxTableViewSectionedReloadDataSource()

在 viewDidLoad() 裡配置 TableViewCell,並把 ViewModel 綁定到 TableView 的資料源:

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(tableView)
    tableView.registerClass(TableViewCell.self, forCellReuseIdentifier: reuseIdentifier)

    dataSource.configureCell = { _, tableView, indexPath, user in
        let cell = tableView.dequeueReusableCellWithIdentifier(self.reuseIdentifier,
                                                             forIndexPath: indexPath) as! TableViewCell
        cell.tag = indexPath.row
        cell.user = user
        return cell
    }

    viewModel.getUsers()
        .bindTo(tableView.rx_itemsWithDataSource(dataSource))
        .addDisposableTo(disposeBag)
}

這裡用的是自訂的 TableViewCell,並給它設了一個 user 屬性。TableViewCell 內部大致如下:

import UIKit

class TableViewCell: UITableViewCell {

    var user: User {
        willSet {
            let string = "\(newValue!.screenName)在簡書上關注了\(newValue!.followingCount)個用戶,並且被\(newValue!.followersCount)個用戶關注了。"

            backgroundColor = tag % 2 == 0 ? UIColor.lightGrayColor() : UIColor.whiteColor()

            textLabel.text = string
            textLabel.numberOfLines = 0
        }
    }
}

我們覆寫了 cell 的 willSet,用它觸發 UI 更新。

回到 viewDidLoad(),最後一行用 Observable 的 getUser 方法取得資料源:viewModel 回傳 SectionModel,tableview 會自動把資料呈現出來,非常省事。

在真機上跑出來的頁面如下:

RxDataSources 的能力很強大。除了 RxTableViewSectionedReloadDataSource,我們還可以用 RxTableViewSectionedAnimatedDataSource 做動畫更新,它對 UICollectionView 也有完善支援。

這個例子還有許多可以擴展的地方。專案的 Demo 已經放在 GitHub 上,需要的話可以直接下載使用。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved