我试图重构代码并创建一个枚举类来保存表视图单元格的indexPath。
我想使代码以这种方式工作:
enum TableViewCell: IndexPath {
case shopImageView = [0,0]
case selectShopImageButton = [0,1] ...
}
,但是编译器说indexPath不是rawRepresentable。如何使indexPath rawRepresentable?该代码目前可以这样工作,我想对其进行改进。
enum TableViewCell {
case shopImageView
case selectShopImageButton
case shopNameLocal
case shopNameEN
case addressLocal
case addressEN
case selectAddressButton
case openingHours
case datePickers
case phone
case email
case uploadShopFormButton
var indexPath: IndexPath {
switch self {
case .shopImageView: return [0,0]
case .selectShopImageButton: return [0,1]
case .shopNameLocal: return [0,2]
case .shopNameEN: return [0,3]
case .addressLocal: return [0,4]
case .addressEN: return [0,5]
case .selectAddressButton: return [0,6]
case .openingHours: return [0,7]
case .datePickers: return [0,8]
case .phone: return [0,9]
case .email: return [0,10]
case .uploadShopFormButton: return [0,11]
}
}
}
答案 0 :(得分:2)
使用硬编码的TableView
IndexPath
的另一种方法是使用具有静态属性的enum
。这样做的好处是,如果您在各种IndexPath
委托方法中引用TableView
,并且需要更改IndexPath
引用,则只需在其中更改一次即可。枚举。
private enum TableIndex {
// Section 0: Information
static let information = IndexPath(row: 0, section: 0)
// Section 1: Preferences
static let notifications = IndexPath(row: 0, section: 1)
static let units = IndexPath(row: 1, section: 1)
static let hapticFeedback = IndexPath(row: 2, section: 1)
// Section 2: Links
static let leaveReview = IndexPath(row: 0, section: 2)
static let support = IndexPath(row: 1, section: 2)
static let privacyPolicy = IndexPath(row: 2, section: 2)
static let disclaimer = IndexPath(row: 3, section: 2)
}
,然后您可以像这样引用它们:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath {
case TableIndex.information:
// do something
case TableIndex.notifications:
// do something
case TableIndex.units:
// do something
// etc
default:
break
}
}
答案 1 :(得分:0)
还有其他方法,但不一定更好,无论如何,您都可以将代码缩减为this。
enum TableViewCell: Int {
case shopImageView = 0
case selectShopImageButton = 1
case shopNameLocal = 2
case shopNameEN = 3
case addressLocal
case addressEN
case selectAddressButton
case openingHours
case datePickers
case phone
case email
case uploadShopFormButton
var indexPath: IndexPath {
return [0, self.rawValue]
}
还请记住,这还取决于您如何使用它们,例如在哪里以及如何传递参数。
其中一种方法。
extension IndexPath {
init(using type: TableViewCell) {
self.init(row: type.rawValue, section: 0)
}
}
let indexPath = IndexPath(using: .shopNameEN)