1

到目前为止,我有以下代码。

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!
    }
}

我需要 Cell1,它是一个静态单元格,并且将始终保持在 indexPath 0 以位于名为“Section1”的部分中,并且所有 Cell2 都位于名为“Section2”的部分中

其他数据源和委托方法;

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 部分在 indexPath 0 处包含 Cell2。

非常感谢任何帮助。

4

1 回答 1

4

根本原因:

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!
    }
}
于 2017-09-02T09:50:26.850 回答