在保护声明中自定义UITableViewCell文本

问题描述 投票:0回答:1

我有一个表视图,该视图从数组数组中读取信息并显示它。表格视图具有可折叠的子类别单元格。我似乎无法弄清楚如何使TableView文本与我创建的原型单元格一致。我为名为“ autoClaimCell”的单元创建了一个.swift文件,单元标识符也为“ autoClaimCell”,该单元内的标签称为“ autoClaimCellLabel”。在我做一个保护声明之前,它可以正常工作,因为它可以让我在声明的末尾放置“ as!autoClaimCell”,然后访问该文件作为标签,但是现在有了保护声明,它将不再让我将“ as!autoClaimCell”放置在其中的任何位置。

这是我的代码:

    func numberOfSections(in tableView: UITableView) -> Int {
        return tableViewData.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableViewData[section].opened == true {
            return tableViewData[section].sectionData.count + 1
        } else {
            return 1
        }
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCell(withIdentifier: "autoClaimCell", for: indexPath) as! autoClaimCell
//        cell.autoClaimCellLabel?.text = areaCategories[indexPath.row]
//        return cell
        let dataIndex = indexPath.row - 1

        if indexPath.row == 0 {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "autoClaimCell") else {return UITableViewCell()}
            cell.textLabel?.text = tableViewData[indexPath.section].title
            return cell
        } else {
            //Use different call indentifier if needed
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "autoClaimCell") else {return UITableViewCell()}
            cell.textLabel?.text = tableViewData[indexPath.section].sectionData[dataIndex]
            return cell
        }

    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            if indexPath.row == 0 {

            if tableViewData[indexPath.section].opened == true {
                tableViewData[indexPath.section].opened = false
                let sections = IndexSet.init(integer: indexPath.section)
                tableView.reloadSections(sections, with: .none) // play around with animations
            } else {
                tableViewData[indexPath.section].opened = true
                let sections = IndexSet.init(integer: indexPath.section)
                tableView.reloadSections(sections, with: .none) // play around with animations
            }
        }
    }

此外,在单元格展开时,如何使显示的清单与过程中的其他单元格原型一致?

ios swift uitableview guard
1个回答
0
投票

guard-let语句中的表达式应为可选值。使用为!将强制拆开将成功或产生故障的可选组件,但从不返回可选组件。只需替换为!与as?

至于符合不同的细胞原型。您需要使用数据模型进行管理。对于索引行0,您已经具有不同的条件。您可以为扩展或类似条件添加条件。

© www.soinside.com 2019 - 2024. All rights reserved.