【问题标题】:Sections in UITableView with Custom CellsUITableView 中带有自定义单元格的部分
【发布时间】:2017-09-02 05:45:57
【问题描述】:

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

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。

非常感谢任何帮助。

【问题讨论】:

  • cellForRowAtIndexPath 中检查indexPath.section 而不是indexPath.row
  • 谢谢,@user1046037 在第二部分的索引 0 上有一些不寻常的行为,但我意识到我需要在 indexPath 方法的高度上也参考该部分。请添加为答案并且不接受它。

标签: swift uitableview sections 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!
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 2016-07-13
    • 2011-11-30
    • 1970-01-01
    相关资源
    最近更新 更多