2016-05-17 72 views
1

我有一個枚舉與幾個案例,我用於計算,用戶將能夠設置一個作爲他們的偏好。他們當然需要能夠改變這種偏好,所以我想在一個表格視圖中顯示它們,以便他們可以看到它們並選擇他們想要設置的偏好。如何使用cellForRowAtIndexPath中的枚舉來填充tableView單元格?

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

的問題是,一個枚舉不具有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] 

哪些工作,但顯然是一個醜陋的黑客。

有沒有更好的方法來做到這一點?

+0

你爲什麼要這樣做,而不是使用「計算」​​結構的「數組」? – Fogmeister

+1

黑客只是看起來很醜,因爲你開始時用一種非常糟糕和醜陋的方式來枚舉枚舉值。每當你用名字列舉一些變量時,就會出現錯誤。給他們有意義的名字或者首先使用數組。 – luk2302

+0

爲什麼不使用switch語句來檢查不同的枚舉情況? – NSGangster

回答

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

Xcode不喜歡: 'let calculation = Calculation(rawValue:indexPath.row + 1)' 它希望我在indexPath.row後添加一個逗號分隔符。當我這樣做時,它抱怨「不能調用類型'Calculation'的初始值設定項的參數列表類型爲'(rawValue:Int,_)' 我試圖將此項添加到我的枚舉中: 'static var cases:Calculation = [計算1,Calculation2,Calculation3 ...等] 的init(_九:智力){ 自= Calculation.cases [九] }' 我那麼做:'讓CELLTEXT = Formula.cases(rawValue :indexPath.row)'不起作用。 – Jim

相關問題