2017-09-02 56 views
0

到目前爲止我有以下代碼。UITableView與自定義單元格中的部分

var someData = [SomeData]() 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    if indexPath.row == 0 { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! Cell1 

     return cell 

    } else { 

     let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as? Cell2 
     let someData = [indexPath.row] 
     //Set up labels etc. 


     return cell! 
    } 
} 

我需要小區1這是一個靜態的細胞,並始終保持在indexPath 0是在一個名爲「SECTION1」例如&所有的小區2的部分是在一個被稱爲「第2節」

其他數據源&委託方法;

func numberOfSections(in tableView: UITableView) -> Int { 
    return 2 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    if section == 0 { 
     return 1 
    } else { 
     return someData.count 
    } 
} 

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    if section == 0 { 
     return "Section1" } 
    else { 
     return "Section2" 
    } 
} 

這將返回我的一切,我需要爲第一部分,然而,當涉及到第二部分(因爲內部cellForRowAtIndex某處的代碼)第2條中包含小區2在indexPath 0

任何幫助不勝感激。

+1

在'cellForRowAtIndexPath'檢查'indexPath.section'而不是'indexPath.row' – user1046037

+0

謝謝@ user1046037在第二部分的索引0處有一些不尋常的行爲,但是我意識到我需要在indexPath方法的高度上引用該部分。請添加爲答案,並接受它。 –

回答

1

根源:

cellForRowAtIndexPath檢查爲indexPath.section代替indexPath.row

修復:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    if indexPath.section == 0 { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! Cell1 

     return cell 

    } else { 

     let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as? Cell2 
     let someData = [indexPath.row] 
     //Set up labels etc. 


     return cell! 
    } 
}