So I have a table view and a searchbar, I implemented the code for the searchbar to filter my array it works just fine but when I click on the cell that I searched it doesn’t display the right information it displays only the information of the first row( first index), note I’m using the global array to pass data from my table view to the View controller so can someone tell me where is my problem in this code how can I solve it .
class SciencesVC: UIViewController ,UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate{
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var TableView: UITableView!
var data = ["د.غادة المطيري", "د.حياة سندي"]
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? DataCell {
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){
myIndex = indexPath.row
performSegue(withIdentifier: "segue", sender: self)
}
}
Values are a global array in SciencesVC:
var Names = ["د.غادة المطيري ","د.حياة سندي "]
var majors = ["الكيمياء","عالمة صيدلية "]
var Communiction = ["-","-",""]
var myIndex = 0
here is the the Detailed UIViewController to show the the information
class ViewController: UIViewController {
@IBOutlet weak var Name: UILabel!
@IBOutlet weak var myImageView: UIImageView!
@IBOutlet weak var major: UILabel!
@IBOutlet weak var info: UITextView!
@IBOutlet weak var twitter: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
Name.text = Names[myIndex]
info.text = infos [myIndex]
myImageView.image = UIImage(named: Names[myIndex] + ".png")
twitter.text = Communiction[myIndex]
}
}