2017-09-19 53 views
0

所以有一組標準的單元格有靜態數據。但是,同樣的UITableView具有單個原型的動態單元。是否可以在UITableView內同時擁有靜態和動態原型單元格。以下是我迄今爲止嘗試:在UITableView中可以混合使用靜態和動態原型單元嗎?

  • 添加UITableView一個UITableView內和自定義之前重新命名內表中的所有重寫方法if tableView == innerTableView
  • 測試它

上述方法不能正常工作甚至基本單元格標籤的文本也沒有被這種嵌套方法修改。

任何幫助將不勝感激。謝謝。

+1

我相信你需要設置不同的自定義單元格,並使用cellForRowAt來返回相關索引路徑中你想要的單元格。另一種可能性是爲每種類型的細胞設置不同的部分。 –

+1

在另一個表格視圖中放置一個表格視圖並不是一個好方法。你想要達到什麼目的?你能展示一個你想達到的結構圖/圖片嗎? – user1046037

+1

您不能在同一個表視圖中同時擁有動態和靜態單元格。使用動態單元格原型,但只爲這些「靜態」單元創建額外的單元格原型,然後讓'cellForRowAt'只根據'indexPath.row'(或其他)將相應重用標識符的單元出列。 – Rob

回答

-1

請不要在另一個UITableView中添加UITableView。你要求用戶體驗和其他方面的泄漏和問題。

您可以用下面的混合細胞類型單一的UITableView:

假設你有你的動態數據的一個NSMutableArray/NSArray的,裏面你的cellForRowAtIndexPath方法,重寫你的靜態細胞與以下:

if (indexPath.row == 0) { 
    //Do static cell setup here 
} 
else if (indexPath.row == 3) { 
    //Do static cell setup here 
} 
else { 
    //Do dynamic cell setup here 
} 
+0

索引索引不是好主意,因爲動態內容包含靜態數量的動態數量的可能性。最好檢查一個類型。 –

0

我在這種情況下通常會做的是創建一個枚舉來表示我想要顯示的行的類型。例如,如果我們想創建一個待辦事項列表視圖控制器,我們要在其中顯示兩個靜態單元格:(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的靜態和動態數據的組合。

相關問題