我在這種情況下通常會做的是創建一個枚舉來表示我想要顯示的行的類型。例如,如果我們想創建一個待辦事項列表視圖控制器,我們要在其中顯示兩個靜態單元格:(1)「歡迎使用待辦事宜應用程序!」 (2)「請輸入您的任務」單元格;和包含待辦事項動力電池,我們可以按如下方式創建一個枚舉:
enum ToDoSectionType {
case welcome // for static cell
case instruction // for static cell
case tasks([Task]) // for dynamic cell
var numberOfRows: Int {
switch self {
case .welcome: return 1
case .instruction: return 1
case let .tasks(tasks): return tasks.count
}
}
}
我們可以創建TableView中一類存儲屬性,像
var sectionsType: [ToDoSectionType]
,併爲其分配正確的值一旦我們已經加載的任務
let tasks = loadTasks()
sectionsType = [.welcome, .instruction, .tasks(tasks)]
然後在TableViewDataSource方法,我們可以實現numberOfRowsInSection和的cellForRowAtIndexPath方法,如
func numberOfSections(in: UITableView) -> Int {
return sectionsType.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionType = sectionsType[section]
return sectionType.numberOfRows
}
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
let sectionType = sectionsType[indexPath.section]
switch sectionType {
case .welcome:
let cell = tableView.dequeueReusableCell(withIdentifier: "WelcomeStaticCell")!
return cell
case .instruction:
let cell = tableView.dequeueReusableCell(withIdentifier: "InstructionStaticCell")!
return cell
case let .tasks(tasks):
let cell = tableView.dequeueReusableCell(withIdentifier: "DynamicTaskCell")!
let task = tasks[indexPath.row]
cell.textLabel?.text = task.name
return cell
}
}
這樣的話,我們可以只使用一個UITableView的靜態和動態數據的組合。
我相信你需要設置不同的自定義單元格,並使用cellForRowAt來返回相關索引路徑中你想要的單元格。另一種可能性是爲每種類型的細胞設置不同的部分。 –
在另一個表格視圖中放置一個表格視圖並不是一個好方法。你想要達到什麼目的?你能展示一個你想達到的結構圖/圖片嗎? – user1046037
您不能在同一個表視圖中同時擁有動態和靜態單元格。使用動態單元格原型,但只爲這些「靜態」單元創建額外的單元格原型,然後讓'cellForRowAt'只根據'indexPath.row'(或其他)將相應重用標識符的單元出列。 – Rob