Search code examples
swifttableviewsections

Add section after 7 cell created in TableView - Swift


I have 2 arrays, one that is containing the sections and another one that is containing the elements for populate the cells of my TableView.

The question is: is it possible to create multiple sections with title after 7 cells?

For example, the array contains 14 elements and sections array 2 elements. I wish that at the beginning will appear "Section 1" then first 7 elements, then "Section 2" then the rest of the elements.

Thank you!

 import UIKit

    class ChallengesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

        @IBOutlet weak var tableView: UITableView!

        var titleArray = [""]
        var weekSection = ["1","2"]

        override func viewDidLoad() {
            super.viewDidLoad()


>      let url = URL(string:"https://website.com/file.txt")!
>         URLCache.shared.removeAllCachedResponses()
>         let task = URLSession.shared.dataTask(with:url) { (data, response, error) in
>             if error != nil {
>                 print(error!)
>             }
>             else {
>                 if let textFile = String(data: data!, encoding: .utf8) {
>                     DispatchQueue.main.async {
>                     self.titleArray = textFile.components(separatedBy: "\n")
>                     self.tableView.reloadData()
>                     print(self.titleArray)
>                     }
>                 }
>             }
>         }
>         task.resume()

        }

         func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return titleArray.count
        }

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

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell = tableView.dequeueReusableCell(withIdentifier: "challengeCell", for: indexPath) as! ChallengeTableViewCell
            cell.labelTitle.text = titleArray[indexPath.row]

            return cell
        }

        func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

            switch (section) {
            case 0:
                return "Case 0"
            case 1:
                return "Case 1"
            default:
                return "Default"
            }
        }

Solution

  • Update numberOfRowsInSection and cellForRowAt methods like this

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Case \(section)"
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        let lastSection = titleArray.count % 7 == 0 ? 0 : 1
        return (titleArray.count/7) + lastSection
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let count = titleArray.count - (7*section)
        return min(7,count)
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "challengeCell", for: indexPath) as! ChallengeTableViewCell
        let rowIndex = (indexPath.section*7)+indexPath.row
        cell.labelTitle.text = titleArray[rowIndex]
        return cell
    }
    

    enter image description here