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

后端 未结 5 1585
旧巷少年郎
旧巷少年郎 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:48

    You could create a Struct to hold the data that belongs to a section, as an alternative to my previous answer. For example:

    struct SectionData {
        let title: String
        let data : [String]
    
        var numberOfItems: Int {
            return data.count
        }
    
        subscript(index: Int) -> String {
            return data[index]
        }
    }
    
    extension SectionData {
        //  Putting a new init method here means we can
        //  keep the original, memberwise initaliser.
        init(title: String, data: String...) {
            self.title = title
            self.data  = data
        }
    }
    

    Now in your view controller you could setup your section data like so:

    lazy var mySections: [SectionData] = {
        let section1 = SectionData(title: "Some Data 1", data: "0, 1", "0, 2", "0, 3")
        let section2 = SectionData(title: "KickAss", data: "1, 0", "1, 1", "1, 2")
    
        return [section1, section2]
    }()
    

    Section Headers

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return mySections.count
    }
    
    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return mySections[section].title
    }
    

    Compared to my previous answer, you now don't have to worry about matching the number of headerTitles to the number of arrays in data.

    TableView Cells

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return mySections[section].numberOfItems
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellTitle = mySections[indexPath.section][indexPath.row]
    
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
        cell.textLabel?.text = cellTitle
    
        return cell
    }
    

提交回复
热议问题