首页 > 解决方案 > UITableView 只显示一个部分

问题描述

我有以下内容UIViewController,其中包含UITableView

class Home : UIViewController {

    override func loadView() {
        self.view = HomeView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

有了这个观点:

class HomeView: UIView {

let tableView = UITableView()
let delegate = TVDelegate()
let dataSource = TVDataSource()

override init(frame: CGRect) {
    super.init(frame: frame)
    createSubviews()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    createSubviews()
}

func createSubviews() {
   setupTableView()
   setupConstraints()
}

func setupTableView() {
    tableView.estimatedRowHeight = 500
    tableView.tableFooterView = UIView()
    tableView.delegate = delegate
    tableView.dataSource = dataSource
    tableView.backgroundColor = UIColor.purple
    tableView.register(TVCell.self, forCellReuseIdentifier: "tableViewCell")
}

func setupConstraints() {
    tableView.prepareView()
    self.addFullSizeView(item: tableView)
}
}

这是我的代表:

class TVDelegate : NSObject, UITableViewDelegate {

func numberOfSections(in tableView: UITableView) -> Int {
    return 5
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 500
}

}

和我的数据源:

class TVDataSource : NSObject, UITableViewDataSource {

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as? TVCell
    {
        return cell
    }
    return UITableViewCell()
}

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

}

但是,当我运行我的应用程序时,我只看到一个带有一个标题的部分,而不是看到 5 个部分。

标签: iosswiftuitableview

解决方案


numberOfSections是一个dataSource方法应该在这里

class TVDataSource : NSObject, UITableViewDataSource { 
  func numberOfSections(in tableView: UITableView) -> Int {
     return 5
  }
}

发生的情况是 tableView 采用默认数字 1 ,TVDataSource因为该方法是可选的,所以它没有在类中实现


推荐阅读