Swift didSelectRowAt在使用搜索栏时会记住第一个元素(indexPath)
我有一个Master-Detail应用程序,其中Master有一个UITable视图,带有一个搜索栏,当单击时会转到Detail视图,其中有一个单击的Master的web视图 在使用搜索之前,一切都很顺利。例如,我在搜索栏中键入“We”作为“威斯敏斯特储蓄信用社”。搜索显示这一点,如第一行所示,在初始加载时属于第一行的“Annie” 我有filteredata[indexPath.row]显示“威斯敏斯特储蓄信用合作社”,它链接到UIImage,因此该图像正确显示了“威斯敏斯特储蓄信用合作社”,然而,urlString仍然显示“Annie”的网站。我不知道如何才能获得“威斯敏斯特储蓄信用社”的相应网站 我已经发布了didSelectRowAt和SearchBar的代码。谢谢Swift didSelectRowAt在使用搜索栏时会记住第一个元素(indexPath),swift,searchbar,Swift,Searchbar,我有一个Master-Detail应用程序,其中Master有一个UITable视图,带有一个搜索栏,当单击时会转到Detail视图,其中有一个单击的Master的web视图 在使用搜索之前,一切都很顺利。例如,我在搜索栏中键入“We”作为“威斯敏斯特储蓄信用社”。搜索显示这一点,如第一行所示,在初始加载时属于第一行的“Annie” 我有filteredata[indexPath.row]显示“威斯敏斯特储蓄信用合作社”,它链接到UIImage,因此该图像正确显示了“威斯敏斯特储蓄信用合作社”,
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()
}
这个标题有误导性。搜索栏不记得第一行。这是您的实现中的一个问题。由于您没有为
if(searchActive==true)
下的MyVariables.urlString
分配任何值,因此它将只使用分配给它的最后一个值
至于如何在if(searchActive==true)
下访问所述值,您必须创建一个filteredSiteAddresses
数组。更新searchBar(\usearchbar:UISearchBar,textDidChange searchText:String)
中的filteredData
数组时,还必须更新filteredSiteAddresses
。然后在if(searchActive==true)
下,您可以执行以下操作
MyVariables.urlString = [MyVariables.filteredSiteAddresses![indexPath.row]]
为什么不必要地获取选定行的单元格,然后不使用它?