gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:07:48 25 4
gpt4 key购买 nike

我正在使用不可点击的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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com