代码之家  ›  专栏  ›  技术社区  ›  Alk

UITableView只显示一个部分

  •  0
  • Alk  · 技术社区  · 5 年前

    我有以下几点 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个部分,而是只看到一个部分有一个标题。

    1 回复  |  直到 5 年前
        1
  •  2
  •   Shehata Gamal    5 年前

    numberOfSections 是一个数据源方法,应该在这里

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

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