ios - 动态自定义 TableView Cell swift

标签 ios swift

我有一个应用程序,我在其中使用带有自定义单元格的 TableView ,效果很好。我现在遇到的问题是我想通过这个使它动态化,单元格的数量不固定。也就是说,单元格可以是 1、2、3 或 5,具体取决于数组的计数。这个单元格 UI 也各不相同

Cell1: could have an image and a label.
Cell2: could have two labels.
Cell3: could have a dayPicker.

当我知道返回的数字时,这是创建单元格的方法

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 3
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "firstTableCell") as! FirstTableCell
        // Set up cell.label
        return cell
    } else if indexPath.row == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "secondTableCell") as! SecondTableCell
        // Set up cell.button
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "thirdTableCell") as! ThirdTableCell
        // Set up cell.textField
        return cell
    }
}

但是现在 numberOfRowsInSection 发生了变化,因此那些 View 项目也是如此。

我该怎么做?以编程方式或其他方式,首选编程方式。

最佳答案

可以使用适当的数据模型来实现动态 TableView 。

例如,使用枚举表示类型,使用带有成员的结构表示类型

enum CellKind {
    case image, label, picker
}

struct Model {
    let kind : CellKind

    // other struct members
}

显示多少个单元格取决于数据源数组中的项目

var items = [Model]()

numberOfRows 中返回项目数

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
}

cellForRow 中,根据类型而不是索引路径显示单元格

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let item = items[indexPath.row]
    switch item.kind {
    case .image:
        let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell") as! ImageCell
        // Set up cell.image
        return cell
    case .label:
        let cell = tableView.dequeueReusableCell(withIdentifier: "labelCell") as! LabelCell
        // Set up cell.label
        return cell
    case .picker:
        let cell = tableView.dequeueReusableCell(withIdentifier: "pickerCell") as! PickerCell
        // Set up cell.picker
        return cell
    }
}

关于ios - 动态自定义 TableView Cell swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56206312/

相关文章:

swift - 增加/减少 waitForDuration()?

ios - 点赞按钮功能无法通过解析工作

ios - 向 UITableView 添加新项目而不替换旧项目

iOS 如何为给定服务器重置 NSURLCredential 或让我的应用程序忘记它曾经与该服务器交谈过?

ios - 在 iOS 6 中调整大小后 MKMapView 变为空白

iphone - 将数据发布到 http iPhone

ios - Swift CLAuthorizationStatus.AlwaysAuthorized 未定义

ios - 导航栏不显示 popViewController Animated() 不工作

ios - 向具有清晰背景的 SCNPlane 添加阴影的问题

ios - 如何将安全区域添加到 View 高度?