繁体   English   中英

动态自定义TableView单元格快速

[英]Dynamic Custom TableView Cell swift

我有一个应用程序,其中使用了带有自定义单元格的表格视图,效果很好。 我现在遇到的问题是我想通过它使其动态化,单元格的数量不是固定的。 也就是说,该单元可以是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有所不同,因此视图项也有所不同。

我怎样才能做到这一点? 以编程方式或其他方式,以编程方式优先。

动态表视图可以使用适当的数据模型来完成。

例如,对种类使用枚举,并使用带有成员的结构指示种类

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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM