【发布时间】:2017-08-30 21:06:39
【问题描述】:
我有一个 UITableView,它有 2 个自定义单元格。自定义单元的类型由我们从 Web 服务获取的键“JourneyType”定义。因此,如果旅程类型是 Solo,我们需要使用 SoloCustomCell 显示单元格,如果旅程类型是 Group,我们需要使用 GroupCustomCell 显示单元格。我的想法是使用枚举来确定分配单元的 Switch 案例。我已经这样定义了枚举:
enum SubscriptionTripType: Int {
case oneWayTrip = 1
case roundTrip
case splitShift
var value: String {
switch self {
case .oneWayTrip:
return NSLocalizedString("One way", comment: "")
case .roundTrip:
return NSLocalizedString("Round trip", comment: "")
case .splitShift:
return NSLocalizedString("Split shift", comment: "")
}
}
}
现在在 cellForRowIndex 中我定义了这样的代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let subscription = mySubscriptionDetails[indexPath.row]
switch subscription.journeyType{
case 0:
let proposePoolcell = tableView.dequeueReusableCell(withIdentifier: "subscriptionCell", for: indexPath) as? MySubscriptionCustomCell
configure(cell: proposePoolcell!, forRowAtIndexPath: indexPath)
return proposePoolcell!
case 1:
let splitShiftCell = tableView.dequeueReusableCell(withIdentifier: "splitShiftCell", for: indexPath) as? SplitShiftSubscriptionCell
return splitShiftCell!
default:break
}
}
Subscription.journeyType 是我们从 Web 服务获得的值。当前订阅数组包含 8 个元素,每个元素都有旅程类型。所以我们需要根据上面定义的枚举来检查case。如何根据 Enum 填充特定旅程类型的单元格。
【问题讨论】:
-
你的问题是什么?怎么了?为什么在 csee 中使用关联 int 值而不是枚举值?您是在问如何将 web 服务中的 int 转换为枚举值?如果是这样,请使用 rawValue
-
@Paulw11 看到我从 web 服务获取 Journey Type 的值作为“单向”。所以我需要检查该值是否为 One-Way 我应该放置“One-Way”的自定义单元格,否则另一个单元格。
-
您是在问如何从字符串 rawValue 初始化枚举值?你读过 Swift Book 关于枚举的章节吗?
-
@Paulw11 是的,我也在问同样的问题
标签: ios swift uitableview enums