gpt4 book ai didi

ios - 动态更新 UITableView 高度和数据

转载 作者:搜寻专家 更新时间:2023-11-01 06:55:37 26 4
gpt4 key购买 nike

我正在实现“按类型搜索”功能,但在动态更新 UITableView 中的行数方面遇到问题。我使用 UISearchBar 并在用户输入三个字母后触发搜索。

我通过异步获取数据的 API 查询搜索结果。这就是我获取结果并更新数据源数组的方式

if let text = searchBar.text {
if text.count >= minSearchStartCriteria {

let tableX:CGFloat = 0
let tableY:CGFloat = searchBar.frame.maxY
let tableWidth:CGFloat = view.frame.width
var tableHeight:CGFloat = 0

// remove the tap recognizer so that the tap on the uitableview
// can be captured
if let tapRecognizer = tapRecognizer,
let recognizers = view.gestureRecognizers {
if recognizers.count > 0 {
view.removeGestureRecognizer(tapRecognizer)
}
}

// create the UITableView
if searchResultsTable == nil {

searchResultsTable = UITableView(frame: CGRect(x: tableX, y: tableY , width: tableWidth, height: tableHeight))

if let searchResultsTable = searchResultsTable {
searchResultsTable.delegate = self
searchResultsTable.dataSource = self
searchResultsTable.register(SearchResultTableViewCell.self, forCellReuseIdentifier: "searchResultTableCell")
view.addSubview(searchResultsTable)
}
}

// update the search results
if let p = onlineSearchPresenter {
p.getSearchResults(request: text) { (results) in
self.searchResults = results
}
tableHeight = CGFloat(searchResults.count * 44)
searchResultsTable?.frame = CGRect(x: tableX, y: tableY, width: tableWidth, height: tableHeight)
searchResultsTable?.reloadData()
}
} else {
// If there is less than "minSearchStartCriteria" letters, remove the table view
searchResults.removeAll()
searchResultsTable?.removeFromSuperview()
searchResultsTable = nil
}
}

如果我输入“abcd”,搜索将返回 10 个结果,因此我的 UITableView 是用 10 行创建的。这里没有问题。然后,如果我继续添加字母并缩小搜索范围,返回的结果数量会减少,比如只有 4 个。我从调试器中检查过,它在 searchResults 数组中显示了正确的结果数量, 但 tableView(_:cellForRowAt:) 仍然尝试从索引 4 获取结果,这超出了一个只有四个项目的数组的范围。

看来我需要让 UITableView 知道数据源数组已更新,以便它更新其索引。我怀疑问题在于更新结果数组的异步性质,但无法弄清楚确切的问题是什么。

我怎样才能完成这项工作?

谢谢

最佳答案

如果您认为问题是由于“更新结果数组的异步性质”引起的,您应该使用去抖动。

使用去抖动,您可以通过在执行之前等待一定时间来限制函数触发的频率。

https://gist.github.com/DoubleREW/567f5e67262f1de781f4f9164235d4e9

https://bradfol.com/how-can-i-debounce-a-method-call-in-swift-4/

关于ios - 动态更新 UITableView 高度和数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53576433/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com