How do I populate two sections in a tableview with two different arrays using swift?

后端 未结 5 1588
旧巷少年郎
旧巷少年郎 2020-12-04 10:09

I have two arrays Data1 and Data2 and I want to populate the data within each of these (they contain strings) into a tableview in two different sections.

The first s

5条回答
  •  眼角桃花
    2020-12-04 10:25

    TableView Cells

    You could use a multidimensional array. For example:

    let data = [["0,0", "0,1", "0,2"], ["1,0", "1,1", "1,2"]]
    

    For the number of sections use:

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return data.count
    }
    

    Then, to specify the number of rows in each section use:

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data[section].count
    }
    

    Finally, you need to setup your cells:

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellText = data[indexPath.section][indexPath.row]
    
        //  Now do whatever you were going to do with the title.
    }
    

    TableView Headers

    You could again use an array, but with just one dimension this time:

    let headerTitles = ["Some Data 1", "KickAss"]
    

    Now to set the titles for the sections:

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section < headerTitles.count {
            return headerTitles[section]
        }
    
        return nil
    }
    

    The code above checks to see there's a title for that section and returns it, otherwise nil is returned. There won't be a title if the number of titles in headerTitles is smaller than the number of arrays in data.

    The Result

    enter image description here

提交回复
热议问题