我有一个 UITableView 应该在部分中包含项目,但只有数组中的第一部分(科学)出现,我不确定它出了什么问题。它应该显示两个部分。
我的代码:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet 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
}
你犯了一个错误,错误的方法。让我们将
numberOfSectionsInTableView(tableView:)
更改为:
func numberOfSections(in tableView: UITableView) -> Int {
return self.section.count
}
在
ViewDidLoad
:
tableView.delegate = self
tableView.dataSource = self