UITableView只显示了一个section。

5

我有一个UITableView,应该有分组的项目,但是只有数组中的第一部分(科学)出现了,我不确定它出了什么问题。它应该显示两个部分。

我的代码:

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




}
2个回答

10
你犯了一个错误,方法不对。让我们把 numberOfSectionsInTableView(tableView:) 改成如下形式:
func numberOfSections(in tableView: UITableView) -> Int {
    return self.section.count
}

0
ViewDidLoad 中:
tableView.delegate = self
tableView.dataSource = self

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接