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

时间:2017-09-19 03:24:57

标签: ios swift uitableview

有一组标准的单元格具有静态数据。但是,相同的 #i1.0 具有单个原型的动态单元。是否可以在UITableView内同时拥有静态和动态原型单元格。这是我到目前为止所尝试的:

  • UITableView中添加UITableView并重命名内部表格
  • 在自定义之前测试所有覆盖方法UITableView

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

2 个答案:

答案 0 :(得分:0)

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

例如,如果我们要创建一个待办事项列表视图控制器,我们要在其中显示两个静态单元格:(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来组合静态和动态数据。

答案 1 :(得分:-1)

请务必不要在另一个UITableView中添加UITableView。您正在询问用户体验和其他方面的泄漏和问题。

您可以使用以下内容创建具有混合单元格类型的单个UITableView:

假设您拥有动态数据的NSMutableArray / NSArray,请在您的cellForRowAtIndexPath方法中,使用以下内容覆盖静态单元格:

if (indexPath.row == 0) {
    //Do static cell setup here
}
else if (indexPath.row == 3) {
    //Do static cell setup here
}
else {
    //Do dynamic cell setup here
}