? ? ? ? 在之前的文章中爵赵,同一個(gè) tableView
里的單元格類型都是一樣的等恐。但有時(shí)我們需要在一個(gè) tableView
里顯示多種類型的數(shù)據(jù)洲劣,這就要求 tableView
可以根據(jù)當(dāng)前行的數(shù)據(jù)自動使用不同類型的 cell
。下面通過樣例演示這個(gè)功能如何實(shí)現(xiàn)课蔬。
九囱稽、同一個(gè) tableView 中使用不同類型的 cell
1,效果圖
(1)tableView
綁定的數(shù)據(jù)源中一共有 2 個(gè) section
二跋,每個(gè) section
里分別有 3 條數(shù)據(jù)需要顯示战惊。
(2)每個(gè) cell
會根據(jù)數(shù)據(jù)類型的不同,自動選擇相應(yīng)的顯示方式:“文字+圖片”或“文字+開關(guān)按鈕”扎即。
2吞获,StroyBoard 設(shè)置
(1)首先拖入一個(gè) tableView
,設(shè)置好相關(guān)約束谚鄙,并與代碼中做 @IBOutlet
關(guān)聯(lián)各拷。
(2)將 tableView
的單元格數(shù)量設(shè)置為 2。
(3)將第一個(gè)單元格的 identifier
設(shè)置成“titleImageCell
”闷营。
接著在該單元格中添加一個(gè) Label
和 ImageView
撤逢,并設(shè)置好相關(guān)約束。同時(shí)將它們的 Tag 分別設(shè)置為 1 和 2粮坞。
(4)將第二個(gè)單元格的 identifier
設(shè)置成“titleSwitchCell
”蚊荣。
接著在該單元格中添加一個(gè)Label
和 Switch
栅炒,并設(shè)置好相關(guān)約束裙顽。同時(shí)將它們的 Tag 分別設(shè)置為 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()
//初始化數(shù)據(jù)
let sections = Observable.just([
MySection(header: "我是第一個(gè)分區(qū)", items: [
.TitleImageSectionItem(title: "圖片數(shù)據(jù)1", image: UIImage(named: "php")!),
.TitleImageSectionItem(title: "圖片數(shù)據(jù)2", image: UIImage(named: "react")!),
.TitleSwitchSectionItem(title: "開關(guān)數(shù)據(jù)1", enabled: true)
]),
MySection(header: "我是第二個(gè)分區(qū)", items: [
.TitleSwitchSectionItem(title: "開關(guān)數(shù)據(jù)2", enabled: false),
.TitleSwitchSectionItem(title: "開關(guān)數(shù)據(jù)3", enabled: false),
.TitleImageSectionItem(title: "圖片數(shù)據(jù)3", image: UIImage(named: "swift")!)
])
])
//創(chuàng)建數(shù)據(jù)源
let dataSource = RxTableViewSectionedReloadDataSource<MySection>(
//設(shè)置單元格
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
}
},
//設(shè)置分區(qū)頭標(biāo)題
titleForHeaderInSection: { ds, index in
return ds.sectionModels[index].header
}
)
//綁定單元格數(shù)據(jù)
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
}
}