我有一个 Master-Detail 应用程序,其中 Master 有一个 UITable View ,带有一个搜索栏,当单击它时会转到 Detail View ,该 View 具有被单击的 master 的 Web View 。
一切顺利,直到使用搜索。例如,我在“Westminster Savings Credit Union”的搜索栏中输入“We”。搜索结果显示在第一行,初始加载时属于第一行的“Annie”。
我有 filteredData[indexPath.row] 显示链接到 UIImage 的“Westminster Savings Credit Union”,因此图像正确显示“Westminster Savings Credit Union”,但是,urlString 仍然显示“Annie”的网站。我不确定如何获得“Westminster Savings Credit Union”的相应网站。
我已经发布了 didSelectRowAt 和 SearchBar 的代码。谢谢。
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath:IndexPath) {
var object2: AnyObject?
if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
switch indexPath.row {
case 0...MyVariables.count-1:
do {
if (searchActive == true) {
object2 = filteredData[indexPath.row] as AnyObject
print("filtereddata", filteredData[indexPath.row]) //prints Westminster Savings Credit Union
//MyVariables.urlString = ? //not sure how to assign it to urlString
print("urlString in didselectrow", MyVariables.urlString)
MyVariables.companyImage = UIImage(named: filteredData[indexPath.row])// correct image
}
else
{
MyVariables.urlString = [MyVariables.siteAddresses![indexPath.row]]
print("MyVariablessiteAddresses",[MyVariables.siteAddresses![indexPath.row]])
print("urlString in didselectrow", MyVariables.urlString)
MyVariables.companyImage = UIImage(named: MyVariables.test![indexPath.row])
}
}
default:
do {
MyVariables.urlString = ["https://sunwoodsquare.com/store-directory/"]
MyVariables.companyImage = UIImage(named: MyVariables.test![indexPath.row])
}
}
}
}
public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredData = (MyVariables.test?.filter { $0.range(of: searchText, options: .caseInsensitive) != nil })!
if(filteredData.count == 0){
searchActive = false;
} else {
searchActive = true;
}
self.tableView.reloadData()
}
最佳答案
标题具有误导性。 searchBar 不记得第一行。这是您实现中的问题。由于您未在 if (searchActive == true)
下为 MyVariables.urlString
分配任何值,因此它只会使用分配给它的最后一个值。
至于如何访问 if (searchActive == true)
下的所述值,您将必须创建一个 filteredSiteAddresses
数组。当您更新 searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
中的 filteredData
数组时,您还必须更新 filteredSiteAddresses
.然后在 if (searchActive == true)
下,你可以做类似的事情
MyVariables.urlString = [MyVariables.filteredSiteAddresses![indexPath.row]]
关于swift - didSelectRowAt 在使用 searchBar 时记住第一个元素(indexPath),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46577638/