OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在 Swift 中将枚举和 switch() 与 UITableViewController 一起使用 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:20
标题: ios - 如何在 Swift 中将枚举和 switch() 与 UITableViewController 一起使用

我的 UITableView 有两个部分,所以我为它们创建了一个枚举:

private enum TableSections {
    HorizontalSection,
    VerticalSection
}

如何使用 numberOfRowsInSection 委托(delegate)方法中传递的“section”变量进行切换?看来我需要将“部分”转换为我的枚举类型?或者有没有更好的方法来做到这一点?

错误是“Enum case "Horizo​​ntalSection"not found in type '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
    }
}



Best Answer-推荐答案


为了做到这一点,你需要给你的枚举一个类型(在这种情况下是 Int):

private enum TableSection: Int {
    horizontalSection,
    verticalSection
}

这使得“horizo​​ntalSection”将被赋值为 0,而“verticalSection”将被赋值为 1。

现在在您的 numberOfRowsInSection 方法中,您需要在枚举属性上使用 .rawValue 以访问它们的整数值:

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
    }
}

关于ios - 如何在 Swift 中将枚举和 switch() 与 UITableViewController 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41214988/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4