tableview有多个部分

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了tableview有多个部分相关的知识,希望对你有一定的参考价值。

我在下面附上了我的代码。

在执行时我只获得一个部分作为输出,但它应该在表视图中返回3个部分。我不知道该怎么做。

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!

    var itemsInSections: Array<Array<String>> = [["1A", "1B", "1C"], ["2A", "2B"], ["3A", "3B", "3C", "3D", "3E"]]
    var sections: Array<String> = ["Section 1", "Section 2", "Section 3"]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.dataSource = self
        self.tableView.delegate = self
    }

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

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

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.sections[section]
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let text = self.itemsInSections[indexPath.section][indexPath.row]

        cell.textLabel!.text = text

        return cell
    }
}
答案

你有错误的方法

替换旧的Swift语法

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

使用New Swift语法

func numberOfSections(in tableView: UITableView) -> Int {
    return self.sections.count
}

以上是关于tableview有多个部分的主要内容,如果未能解决你的问题,请参考以下文章

kotlin-从一个片段更改多个片段的小数位

在 Swift 中的数组中使用多个部分和多个字典填充 TableView

多个位置的相同TableView swift 3

UIButton状态在用多个部分滚动tableview时改变 - Swift

将 UITableView 排序为多个部分

在具有多个部分的 tableView 中滚动时使用平滑动画更改视图背景渐变颜色