【问题标题】:Customize the UITableViewCell text inside a guard statement自定义保护语句中的 UITableViewCell 文本
【发布时间】:2020-03-21 08:19:04
【问题描述】:

我有一个表格视图,它从数组数组中读取信息并显示它。表格视图具有用于子类别的可折叠单元格。我似乎无法弄清楚如何使我的 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
            }
        }
    }

另外,如何使单元格展开时显示的列表符合流程中的不同单元格原型?

【问题讨论】:

  • 我明白了,你有 2 个tableViewCell 课程?还是 2 个标识符?
  • 不,它们 tableView 单元格标识符和 tableViewCell swift 类是相同的名称。戴尔关于切换“!”的回答是正确的。到一个“?”。

标签: ios swift uitableview guard


【解决方案1】:

guard-let 语句中的表达式应计算为可选值。用作!将强制打开可选项,这将成功或生成错误,但从不返回可选项。 只需替换为!用 as?

至于符合不同的细胞原型。你需要用你的数据模型来管理它。您已经为索引第 0 行设置了不同的条件。您可以添加条件为 if expand 等。

【讨论】:

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