How to use an enum and switch() with UITableViewController in Swift

后端 未结 3 1013
刺人心
刺人心 2021-01-13 17:51

My UITableView has two sections, so I created an enum for them:

private enum TableSections {
    HorizontalSection,
    VerticalSection
}

H

3条回答
  •  天命终不由人
    2021-01-13 17:59

    In order to do this, you need to give your enum a type (Int in this case):

    private enum TableSection: Int {
        horizontalSection,
        verticalSection
    }
    

    This makes it so that 'horizontalSection' will be assigned the value 0 and 'verticalSection' will be assigned the value 1.

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

提交回复
热议问题