当我运行应用程序时,仅调用 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!
}
我尝试了很多次,但它对我不起作用。即使在控制台中也没有显示错误。代码有问题吗?
最佳答案
如果numberOfRowsInSection
被调用,但没有其他UITableViewDataSource
方法是,这必定意味着 numberOfRowsInSection
返回 0。这必定意味着 arrSearch
是空的。另外,这部分代码
if let arr = UserDefault["SearchTo"] {
arrSearch.append(arr as! [String:Any])
}
应该重写。由于您正在转换下标的结果,因此您可以将其作为 if let
的一部分来执行。 ,如果结果不是 [String:Any]
,这也会使它更安全类型
if let arr = UserDefault["SearchTo"] as? [String:Any] {
arrSearch.append(arr)
}
简而言之,显然UserDefault["SearchTo"]
返回nil
关于ios - Swift:只调用一个 TableView 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53682408/