首页 > 解决方案 > 当 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)
}

标签: iosswift

解决方案


假设您的搜索者正确地重新加载了您的表格视图,您可以将检查放在您的委托方法中;当 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 
}

推荐阅读