如何在cellForRowAtIndexPath中使用枚举来填充tableView单元格?

时间:2016-05-17 14:09:54

标签: swift uitableview enums

我有一个包含我用于计算的几个案例的枚举,用户可以设置一个作为他们的偏好。他们当然需要能够改变这种偏好,所以我想在表格视图中显示它们,这样他们就可以看到所有这些并选择他们想要设置的偏好。

enum Calculation: Int {

    case Calculation1

    case Calculation2

    case Calculation3

    case Calculation4

    case Calculation5

    case Calculation6

    case NoChoice // this exist only for the little trick in the refresh() method for which I need to know the number of cases

    // This static method is from http://stackoverflow.com/questions/27094878/how-do-i-get-the-count-of-a-swift-enum/32063267#32063267
static let count: Int = {
    var max: Int = 0
    while let _ = Calculation(rawValue: max) { max += 1 }
    return max
    }()

    static var selectedChoice: String {
        get {
            let userDefaults = NSUserDefaults.standardUserDefaults().objectForKey("selectedCalculation")
            if let returnValue = userDefaults!.objectForKey("selectedCalculation") as? String { 
                return returnValue // if one exists, return it
            } else {
        return "Calculation1" // if not, return this default value
    }
  }
    set {
        NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "selectedCalculation")
        NSUserDefaults.standardUserDefaults().synchronize()
    }
  }
 }

问题是enum没有indexPath,所以我不能遍历它并获取这些案例名称:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("formulaCell", forIndexPath: indexPath)

    // Configure the cell...
    let currentFormula = Calculation[indexPath.row] <- Error: Type 'Calculation.Type' has no subscript members
    cell.textLabel?.text = currentFormula
    return cell
}

我能想到的最好的方法是创建这些案例的数组并用它来创建单元格:

let Calculation = [Calculation1, Calculation2, Calculation3 ...etc] 

虽然有效,但显然是一个丑陋的黑客。

有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

在枚举上使用switch语句来处理每个案例的创建单元格。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("formulaCell", forIndexPath: indexPath)
    let calculation = Calculation(rawValue: indexPath.row + 1) //Start at 1 and add one.

    switch calculation {
        case .Calculation1:
             //Configure cell for case 1
        case .Calculation2
        //Configure cell for case 2 etc...
        default:
    }

    return cell
}