Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView only displays one section

I have a UITableView that is supposed to have items in sections but only the first section (Science) in the array is appearing and I'm not sure what's wrong with it. It should be displaying both sections.

My code:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
    @IBOutlet weak var tableView: UITableView!
    var checked = [Bool]()



    let section = ["Science", "Math"]

    let items = [["Physics", "Biology", "Chemistry"], ["Algebra I", "Algebra II", "Statistics"]]






    override func viewDidLoad(){
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
         self.tableView.allowsMultipleSelection = true

    }

    override func didReceiveMemoryWarning(){
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return self.items[section].count
    }

     func numberOfSectionsInTableView(tableView: UITableView) -> Int{
        // #warning Incomplete implementation, return the number of sections

        return self.section.count

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

        return self.section[section]

    }
    //All before.

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 

        cell.textLabel?.text = self.items[indexPath.section][indexPath.row]

        //MARK: -Checkmark and save support.
        cell.accessoryType = cell.isSelected ? .checkmark : .none
        cell.selectionStyle = .none // to prevent cells from being "highlighted"

        return cell
    }


    //MARK: - Checkmark and save functions.


     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark

    }

     func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        tableView.cellForRow(at: indexPath)?.accessoryType = .none
    }



    //MARK: - Sections




}
like image 762
Matt Avatar asked Jan 04 '23 17:01

Matt


1 Answers

You made a mistake, wrong method. Let change numberOfSectionsInTableView(tableView:) to:

func numberOfSections(in tableView: UITableView) -> Int {
    return self.section.count
}
like image 74
Danh Huynh Avatar answered Jan 15 '23 17:01

Danh Huynh