Ios 是否可以在UITableView中混合使用静态和动态原型单元?

Ios 是否可以在UITableView中混合使用静态和动态原型单元?,ios,swift,uitableview,Ios,Swift,Uitableview,有一组标准的单元格具有静态数据。但是,相同的UITableView具有单个原型的动态单元。是否可以在UITableView中同时拥有静态和动态原型单元。以下是我迄今为止所尝试的: 在UITableView中添加UITableView并重命名内部表 如果tableView==innerTableView在定制之前,在所有重写方法中进行测试 上述方法不起作用,甚至基本单元格标签的文本也没有使用这种嵌套方法进行修改。在这种情况下,我通常要做的是创建一个枚举,表示要显示的行的类型 例如,如果我们要创

有一组标准的单元格具有静态数据。但是,相同的
UITableView
具有单个原型的动态单元。是否可以在
UITableView
中同时拥有静态和动态原型单元。以下是我迄今为止所尝试的:

  • UITableView
    中添加
    UITableView
    并重命名内部表
  • 如果tableView==innerTableView在定制之前,在所有重写方法中进行测试

上述方法不起作用,甚至基本单元格标签的文本也没有使用这种嵌套方法进行修改。

在这种情况下,我通常要做的是创建一个枚举,表示要显示的行的类型

例如,如果我们要创建一个待办事项列表视图控制器,其中我们要显示两个静态单元格:(1)“欢迎使用待办事项!”单元格,(2)“请输入您的任务”单元格;和包含待办事项的动态单元格,我们可以按如下方式创建枚举:

enum ToDoSectionType {
    case welcome // for static cell
    case instruction // for static cell
    case tasks([Task]) // for dynamic cell

    var numberOfRows: Int {
        switch self {
        case .welcome: return 1
        case .instruction: return 1
        case let .tasks(tasks): return tasks.count
        }
    }
}
我们可以在TableView类中创建一个存储属性,如

var sectionsType: [ToDoSectionType]
一旦我们已经加载了任务,就给它分配正确的值

let tasks = loadTasks()
sectionsType = [.welcome, .instruction, .tasks(tasks)]
然后在TableViewDataSource方法中,我们可以实现numberOfRowsInSection和cellForRowAtIndexPath方法,如

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

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let sectionType = sectionsType[section]
    return sectionType.numberOfRows
}

func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
    let sectionType = sectionsType[indexPath.section]
    switch sectionType {
    case .welcome:
        let cell = tableView.dequeueReusableCell(withIdentifier: "WelcomeStaticCell")!
        return cell
    case .instruction:
        let cell = tableView.dequeueReusableCell(withIdentifier: "InstructionStaticCell")!
        return cell
    case let .tasks(tasks):
        let cell = tableView.dequeueReusableCell(withIdentifier: "DynamicTaskCell")!
        let task = tasks[indexPath.row]
        cell.textLabel?.text = task.name
        return cell
    }
}

这样,我们可以只使用一个UITableView组合静态和动态数据。

我认为您需要设置不同的自定义单元格,并使用cellForRowAt返回您想要在相关IndExpath中使用的单元格。另一种可能是对每种类型的单元格都有单独的部分。在另一个表视图中有一个表视图不是一个好方法。你到底想要实现什么?你能展示一个你想要实现的方框图/图片吗?你不能在同一个表视图中同时有动态和静态单元格。使用动态单元原型,但只需为那些“静态”单元创建额外的单元原型,然后让
cellForRowAt
根据
indexPath.row
(或任何内容)将适当重用标识符的单元出列即可@Rob将单元格从静态更改为动态将不再允许您将插座引用到视图控制器,因此这不是“仅仅”这样做,而是大量的额外工作。可能会重复