? ? ? ? 在之前的文章中,同一個 tableView
里的單元格類型都是一樣的。但有時我們需要在一個 tableView
里顯示多種類型的數據,這就要求 tableView
可以根據當前行的數據自動使用不同類型的 cell
。下面通過樣例演示這個功能如何實現。
九、同一個 tableView 中使用不同類型的 cell
1,效果圖
(1)tableView
綁定的數據源中一共有 2 個 section
,每個 section
里分別有 3 條數據需要顯示。
(2)每個 cell
會根據數據類型的不同,自動選擇相應的顯示方式:“文字+圖片”或“文字+開關按鈕”。
2,StroyBoard 設置
(1)首先拖入一個 tableView
,設置好相關約束,并與代碼中做 @IBOutlet
關聯。
(2)將 tableView
的單元格數量設置為 2。
(3)將第一個單元格的 identifier
設置成“titleImageCell
”。
接著在該單元格中添加一個 Label
和 ImageView
,并設置好相關約束。同時將它們的 Tag 分別設置為 1 和 2。
(4)將第二個單元格的 identifier
設置成“titleSwitchCell
”。
接著在該單元格中添加一個Label
和 Switch
,并設置好相關約束。同時將它們的 Tag 分別設置為 1 和 2。
3,樣例代碼
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
//初始化數據
let sections = Observable.just([
MySection(header: "我是第一個分區", items: [
.TitleImageSectionItem(title: "圖片數據1", image: UIImage(named: "php")!),
.TitleImageSectionItem(title: "圖片數據2", image: UIImage(named: "react")!),
.TitleSwitchSectionItem(title: "開關數據1", enabled: true)
]),
MySection(header: "我是第二個分區", items: [
.TitleSwitchSectionItem(title: "開關數據2", enabled: false),
.TitleSwitchSectionItem(title: "開關數據3", enabled: false),
.TitleImageSectionItem(title: "圖片數據3", image: UIImage(named: "swift")!)
])
])
//創建數據源
let dataSource = RxTableViewSectionedReloadDataSource<MySection>(
//設置單元格
configureCell: { dataSource, tableView, indexPath, item in
switch dataSource[indexPath] {
case let .TitleImageSectionItem(title, image):
let cell = tableView.dequeueReusableCell(withIdentifier: "titleImageCell",
for: indexPath)
(cell.viewWithTag(1) as! UILabel).text = title
(cell.viewWithTag(2) as! UIImageView).image = image
return cell
case let .TitleSwitchSectionItem(title, enabled):
let cell = tableView.dequeueReusableCell(withIdentifier: "titleSwitchCell",
for: indexPath)
(cell.viewWithTag(1) as! UILabel).text = title
(cell.viewWithTag(2) as! UISwitch).isOn = enabled
return cell
}
},
//設置分區頭標題
titleForHeaderInSection: { ds, index in
return ds.sectionModels[index].header
}
)
//綁定單元格數據
sections
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
}
}
//單元格類型
enum SectionItem {
case TitleImageSectionItem(title: String, image: UIImage)
case TitleSwitchSectionItem(title: String, enabled: Bool)
}
//自定義Section
struct MySection {
var header: String
var items: [SectionItem]
}
extension MySection : SectionModelType {
typealias Item = SectionItem
init(original: MySection, items: [Item]) {
self = original
self.items = items
}
}