首页 > 解决方案 > Swift:只调用了一个 TableView 方法

问题描述

当我运行应用程序时,只numberOfRowsInSection()调用方法。所以我在每个方法中放置了一定数量的断点,但我发现它numberOfRowsInSection()被调用了 4-5 次,其余的方法没有被调用。这是我的代码。

import UIKit


var arrSearch = [[String:Any]]()
class RecentSearchViewController: CustomNavigationViewController {
    @IBOutlet var tblSearch: UITableView!

    var searchBusVC:SearchBusViewController?
    override func viewDidLoad() {
        super.viewDidLoad()

          if let arr = UserDefault["SearchTo"]{ 
          arrSearch.append(arr as! [String:Any])
        } 
        tblSearch.reloadData()
    }

extension RecentSearchViewController: UITableViewDataSource , UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrSearch.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 200
    }
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "RecentCell") as! RecentCell
        cell.selectionStyle = .none
        let dict = arrSearch[indexPath.row]
        cell.lblFrom.text = (dict["From"] as! String)
        cell.lblTo.text = (dict["To"] as! String)
        let strDate = Utill.getStringFromDate("EEE MMM dd ,yyyy", date: (dict["fromdate"] as! Date))
        cell.lblDate.text = strDate
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let searchvc = self.searchBusVC {
            searchvc.setRecentSearch(dict: arrSearch[indexPath.row])

        }
        self.navigationController?.popViewController(animated: true)
    }

}


class RecentCell: UITableViewCell {
    @IBOutlet var lblFrom: UILabel!
    @IBOutlet var lblTo: UILabel!
    @IBOutlet var lblDate: UILabel!

}

我尝试了很多次,但它对我不起作用。即使在控制台中也没有显示错误。代码有问题吗?

标签: iosswiftuitableview

解决方案


If numberOfRowsInSection is called, but no other UITableViewDataSource methods are, that must mean that numberOfRowsInSection returns 0. And that must mean that arrSearch is empty. Also, this part of code

if let arr = UserDefault["SearchTo"] { 
      arrSearch.append(arr as! [String:Any])
}

Should be rewritten. Since you are casting the result of subscript, you can do that as a part of if let, which would also make it safer if the result isn't of [String:Any] type

if let arr = UserDefault["SearchTo"] as? [String:Any] { 
      arrSearch.append(arr)
}

In short, apparently UserDefault["SearchTo"] returns nil


推荐阅读