ios - 当 Swift 中只显示一个结果时,如何以编程方式“点击”UITableview 单元格
问题描述
我有一个 iOS 应用程序,它显示来自 UItableview 中搜索栏的搜索结果。目前,用户必须点击其中一个搜索结果才能发生转场。我想要做的是,如果搜索结果只显示一个结果,segue 会自动发生。以下是我当前的代码。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! ProductViewController
let product:Product!
if(isSearchActive){
product = filterProducts[(tblProducts.indexPathForSelectedRow?.row)!]
} else {
product = products[(tblProducts.indexPathForSelectedRow?.row)!]
}
vc.product = product
}
}
extension SearchViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(isSearchActive){
return filterProducts.count
}
return products.count
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ProductTableViewCell") as! ProductTableViewCell
let product:Product!
if(isSearchActive){
product = filterProducts[indexPath.row]
} else {
product = products[indexPath.row]
}
cell.initUI(product)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "gotoProduct", sender: self)
}
解决方案
假设您的搜索者正确地重新加载了您的表格视图,您可以将检查放在您的委托方法中;当 tableview 检查行数时,如果您正在搜索并且有一个结果,则执行 segue。
extension SearchViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(isSearchActive){
if filterProducts.count == 1 {
performSegue(withIdentifier: "gotoProduct", sender: self)
}
return filterProducts.count
}
return products.count
}
推荐阅读
- python - 为什么在 Python 中导入我自己的模块时出现语法错误
- powerbi - IF 条件 DAX 用于度量的多个条件
- perl - 在进程之间共享和修改 PSGI 中的变量
- rust - 未能在阶乘函数中解析为 Rust 中的 Trait
- javascript - 无法通过本地服务器运行 Vega-Lite 可视化示例
- flutter - 如何正确混合状态?
- matlab - 如何在矩阵的特定范围内添加一些值?
- django - 将模型保存在数据库中的过程很慢
- javascript - 范围问题:将帐户凭据存储在承诺中的新类对象中,但现在需要在类的其余部分中使用此对象
- python - 将图像两次发送到 CouchDb 而不是 1 次