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

Variable use of multiple custom cells

我正在使用一个不可点击的tableView 来显示一个对象的不同信息。 对于这些信息,我有不同的自定义单元格类型,一种是我放置地图的地方,如果我的对象有位置,一种是带有链接的列表,另一种是多行标签,用于一些小的描述......例如。

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

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
}

}

到目前为止一切顺利,一切正常。我的问题是,并非每个对象都需要地图,其中一些只需要一些文本和列表,其他对象需要地图和列表,其他所有对象。如果有条件,我希望我的 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 {
    ...
}...
}

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

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

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
}

然后在 table 视图方法中查看当前 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 数组中项目的顺序即可。