2015-04-11 3 views
0

Допустим, что у меня есть три массива в моем ViewController. Два из них представляют ячейки секций, а один представляет разделы.Как добавить TableViewCell к определенному разделу в Swift

Как добавить TableViewCell к определенному разделу?

ViewController.swift:

// represents my 2 sections 
var sectionNames = ["Switches","Settings"] 

// data for each section 
var switchData = ["switch1","switch2", "switch3"] 
var settingData = ["setting1", "setting2"] 

ответ

1

Лучше было бы использовать словарь вместо отдельных массивов:

let data: Dictionary<String,[String]> = [ 
    "Switches": ["switch1","switch2","switch3"], 
    "Settings": ["setting1","setting2"] 
] 

Здесь ключи словаря являются разделы и значения массивов являются данными для каждого раздела.

Таким образом, tableViewController может выглядеть следующим образом:

class MyTableViewController: UITableViewController { 
    let data: Dictionary<String,[String]> = [ 
     "switches": ["switch1","switch2","switch3"], 
     "settings": ["setting1","setting2"] 
    ] 

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     // Return the number of sections. 
     return data.count 
    } 

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     // Return the number of rows in the section. 
     let sectionString = Array(data.keys)[section] 

     return data[sectionString]!.count 
    } 

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
     let sectionString = Array(data.keys)[section] 
     return sectionString 
    } 

    override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { 
    } 

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

     // Configure the cell... 
     let sectionString = Array(data.keys)[indexPath.section] 
     cell.textLabel?.text = data[sectionString]![indexPath.row] 

     return cell 
    } 

} 

Результат:

enter image description here

+0

спасибо за совет, могли бы вы показать мне реализация? Вот где у меня проблемы. Или даже просто укажите мне, в каком методе tableView я должен использовать. –

+1

Я обновил свой ответ – zisoft

+0

очень приятно, спасибо, что нашли время, чтобы собрать это вместе zisoft –

Смежные вопросы