如何在Swift中使用带有UITableViewController的枚举和switch() [英] How to use an enum and switch() with UITableViewController in Swift
问题描述
我的UITableView有两个部分,所以我为它们创建了一个枚举:
My UITableView has two sections, so I created an enum for them:
private enum TableSections {
HorizontalSection,
VerticalSection
}
如何切换sectionvar传递给numberOfRowsInSection委托方法?看来我需要将section转换为我的枚举类型?或者有更好的方法来实现这一目标吗?
How do I switch with the "section" var passed in numberOfRowsInSection delegate method? It seems that I need to cast "section" to my enum type? Or is there a better way to accomplish this?
错误是Enum caseHorizontalSection在类型'int'中找不到。
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case .HorizontalSection:
return firstArray.count
case .VerticalSection:
return secondArray.count
default
return 0
}
}
推荐答案
为了做到这一点,你需要给你的枚举一个类型(在这种情况下为Int):
In order to do this, you need to give your enum a type (Int in this case):
private enum TableSection: Int {
horizontalSection,
verticalSection
}
这使得'horizontalSection'将被赋值为0,'verticalSection'将被赋值为1.
This makes it so that 'horizontalSection' will be assigned the value 0 and 'verticalSection' will be assigned the value 1.
现在在你的 numberOfR owsInSection
方法,你需要在枚举属性上使用 .rawValue
来访问它们的整数值:
Now in your numberOfRowsInSection
method you need to use .rawValue
on the enum properties in order to access their integer values:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case TableSection.horizontalSection.rawValue:
return firstArray.count
case TableSection.verticalSection.rawValue:
return secondArray.count
default:
return 0
}
}
这篇关于如何在Swift中使用带有UITableViewController的枚举和switch()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!