ios - 多个自定义单元格的可变使用

标签 ios swift uitableview custom-cell

我正在使用不可点击的tableView来显示一个对象的不同信息。 对于此信息,我有不同的自定义单元格类型,其中一个单元格类型是我放置 map 的位置,如果我的对象有位置,一个单元格类型有一个带链接的列表,另一个单元格类型有一个多行标签用于一些说明......例如。

我通过以下方式管理此单元格:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

if indexPath.row == 0 {
    let cell: mapCell = tableView.dequeueReusableCellWithIdentifier("mapCell") as! MapCell
    return cell
} else if indexPath.row == 1 {
    let cell: textCell = tableView.dequeueReusableCellWithIdentifier("textCell") as! TextCell
    return cell
} else if indexPath.row == 2 {
    let cell: listCell = tableView.dequeueReusableCellWithIdentifier("listCell") as! ListCell
    return cell
}

}

到目前为止一切顺利,一切正常。我的问题是,并不是每个对象都需要 map ,其中一些只需要一些文本和列表,其他对象需要 map 和列表,其他所有对象都需要。如果有条件,我希望我的 tableView 跳过一些单元格。

我知道,我可以创建一个符号数组来更改 tableView 的单元格数量,但只是从 tableView 的末尾删除,而不是特定的单元格。

我的想法之一是生成一个空单元格,高度可能为 0 或 1,以便我可以执行以下操作:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

if indexPath.row == 0 {
    if mapCellNeeded {
          let cell: mapCell = tableView.dequeueReusableCellWithIdentifier("mapCell") as! mapCell
    } else {
          let cell: emptyCell = tableView.dequeueReusableCellWithIdentifier("emptyCell") as! EmptyCell
    }
    return cell
} else if indexPath.row == 1 {
    ...
}...
}

不知道有没有有效的方法。希望大家能够帮助我。

最佳答案

您的解决方案可行。另一种方法(非常好且快速)不是对行号进行硬编码,而是使用枚举:

enum InfoCellType {
case Map
case Text
case Links
}

... 

var rows = [InfoCellType]()
... 
// when you know what should be there or not
func constructRows() {

if (mapCellNeeded) {
rows.append(InfoCellType.Map)
}
rows.append(InfoCellType.Text)
... etc
}

然后在 TableView 方法中查看当前indexPath的类型:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cellType: InfoCellType = self.rows[indexPath.row]
switch cellType {
case .Map:
    let cell: mapCell = tableView.dequeueReusableCellWithIdentifier("mapCell") as! mapCell 
    return cell
case .Text:
    ...
case.Links:
    ...
}
}

此解决方案还允许轻松更改行的顺序 - 只需更改 rows 数组中项目的顺序即可。

关于ios - 多个自定义单元格的可变使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39129541/

相关文章:

ios - 使用 Xib 在 Tableview header 中快速重新加载 CollectionView

ios - 快速互斥替代品

ios - 如何调整 TableView 中自定义单元格的大小?

IOS 5静态tableview单元格没有背景颜色

ios - 删除动画期间行数更改时 UITableView 中的内部不一致

iphone - viewDidAppear 高度在 iPhone 5 中为 656

ios - 如何实现 IFTTT 的动画介绍屏幕?

objective-c - UIButton不显示文字设置宽度[UIButton setTitle]

ios - GMSMapView 显示空白 map

ios - 无法使用协变类型 'refreshControl' 覆盖类型 'UIRefreshControl?' 的可变属性 'UIRefreshControl'