2016-07-24 22 views
3
與UITableViewController中使用枚舉和開關()

我的UITableView有兩個部分,所以我創建了他們的枚舉:如何斯威夫特

private enum TableSections { 
    HorizontalSection, 
    VerticalSection 
} 

如何與「部分」開關VAR在numberOfRowsInSection通過委託方法?看來我需要爲我的枚舉類型投下「部分」?還是有更好的方法來完成這個?

「枚舉案‘Horizo​​ntalSection’的類型不‘詮釋’發現的錯誤。

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    switch section { 

    case .HorizontalSection: 
     return firstArray.count 

    case .VerticalSection: 
     return secondArray.count 

    default 
     return 0 
    } 
} 
+0

可以使用原始值。 – tktsubota

回答

5

爲了做到這一點,你需要給你的枚舉類型(智力在這種情況下) :

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

即使@tktsubota指出我正確的方向,你回答完整的答案。我將這個標記爲答案。謝謝。 – KevinS

+1

關於命名約定的一個說法是:「給出枚舉類型單數而不是複數名稱,以便它們讀作不言自明」,因此最好使用TableSection iso TableSections作爲枚舉的名稱(cfr [Swift Programming Language guidelines](https:/ /developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html)) – Herre

+0

@感謝您的關注,我將對其進行修改以顯示更改 –

2

好吧,我想通了,感謝@tktsubota指着我在正確的方向。我對Swift很陌生。我看着.rawValue並做出了一些改變:

private enum TableSections: Int { 
    case HorizontalSection = 0 
    case VerticalSection = 1 
} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    switch section { 

    case TableSections.HorizontalSection.rawValue: 
     return firstArray.count 

    case TableSections.VerticalSection.rawValue: 
     return secondArray.count 

    default 
     return 0 
    } 
} 
1

傑夫·劉易斯卻是正確的,要詳細說說,讓代碼更準備litlle位 - >我處理這些事情的方式是:

  1. 實例化枚舉與原始值 - >區段索引

guard let sectionType = TableSections(rawValue: section) else { return 0 }

  • 第類型使用開關
  • switch sectionType { case .horizontalSection: return firstArray.count case .verticalSection: return secondArray.count }