如何为 Swift Xcode 的 Searchbar 调用数组 [英] How do I call an array for Searchbar for Swift Xcode
本文介绍了如何为 Swift Xcode 的 Searchbar 调用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
选择tableview单元格后如何获得正确的viewcontroller你能帮我我认为我的索引有问题
How do I get the correct viewcontroller after selecting a tableview cell can you please help me I think there is a problem with my index
import UIKit
var NamesC = [ "one", "two"]
var IndexC = 0
class ComputerVC: UIViewController ,UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate{
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var TableView: UITableView!
var data = [ "one", "two"]
var filteredData = [String]()
var inSearchMode = false
override func viewDidLoad() {
super.viewDidLoad()
TableView.delegate = self
TableView.dataSource = self
searchBar.delegate = self
searchBar.returnKeyType = UIReturnKeyType.done
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if inSearchMode {
return filteredData.count
}
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? DataCellC {
let text: String!
if inSearchMode {
text = filteredData[indexPath.row]
} else {
text = data[indexPath.row]
}
cell.congigureCell(text: text)
return cell
} else {
return UITableViewCell()
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
inSearchMode = false
view.endEditing(true)
TableView.reloadData()
} else {
inSearchMode = true
filteredData = data.filter({$0.contains(searchBar.text!)})
TableView.reloadData()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
IndexC = indexPath.row
performSegue(withIdentifier: "segue", sender: self)
}
}
推荐答案
问题在这里:
Name.text = NamesC[IndexC]
您的数组已过滤,您的 indexC 是您在过滤后的数组中使用的那个.
Your array is filtered, your indexC is the one you used in the filtered array.
您可以定义一个过滤数组FNamesC
,并在您在搜索栏和视图控制器中搜索时更新此数组
You can define a filtered array FNamesC
, and update this array when you search in your search bar and in your viewController
Name.text = FNamesC[IndexC]
我不知道你为什么想要一个全局数组.
I don't know why you want a global array though.
这篇关于如何为 Swift Xcode 的 Searchbar 调用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文