ios - 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!
}
我尝试了很多次,但它对我不起作用。即使在控制台中也没有显示错误。代码有问题吗?
解决方案
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
推荐阅读
- python - 使用 django 和 rest framweork 的错误 url
- c# - 我需要使用 CreateObject() 从 VB6 COM 自动化重新启动 .NET WPF 应用程序
- java - hibernate 无法连接 Heroku postgresql 插件
- html - 我的元素的边距来自哪里?
- python - 一对的Python概率
- c++ - 无法使用 CMakeLists 编译英特尔 MKL 测试代码
- javascript - 为什么我不能创建一个“for / in”循环遍历同一对象中的值的方法?
- r - 如何从同一订单的多个价格和付款金额创建运行余额?
- html - 如何使用css网格选择整个网格项目,同时保持项目中心对齐并且在悬停时仍然保持
- android - 按周和月创建统计图表android