前提・実現したいこと
学習のため、メモ帳アプリを作っておりSearchBarで検索出来る機能を作っているのですが、
検索結果をTableViewに表示する段階までは実装出来たのですが、検索結果のCellをタップしても、別のメモが開いてしまう状況です。
該当のソースコード
import UIKit // textViewに入力された文字を格納する変数 var memoText = [String]() var honIndex = -1 class ViewController: UIViewController { // 編集のために全画面から値を受け取る var aDate: String = "" @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() // 編集のために設定 textView.text = aDate } @IBAction func setButton(_ sender: Any) { // -1は新規作成なので追加、それ以外はmemoTextを書き換え if honIndex == -1 { memoText.append(textView.text!) } else { memoText[honIndex] = textView.text! } // memoTextをUserDefaultsで保存する UserDefaults.standard.set(memoText, forKey: "memoTextKey") } }
import UIKit class TableViewController: UITableViewController,UISearchBarDelegate { @IBOutlet weak var searchBar: UISearchBar! // 検索結果を格納 var searchResult = [String]() override func viewDidLoad() { super.viewDidLoad() searchBar.delegate = self if UserDefaults.standard.object(forKey: "memoTextKey") != nil { memoText = UserDefaults.standard.object(forKey: "memoTextKey") as! [String] } } override func viewDidAppear(_ animated: Bool) { // TableView更新 tableView.reloadData() // 前画面から戻ってきたらhonIndexを初期化 honIndex = -1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchBar.text != "" { return searchResult.count } else { return memoText.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // cellの表示内容を設定 let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) if searchBar.text != "" { cell.textLabel!.text = "(searchResult[indexPath.row])" } else { cell.textLabel!.text = memoText[indexPath.row] } return cell } // Cellを押した時の処理 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // honIndexに押されたCell番号を格納する honIndex = indexPath.row performSegue(withIdentifier: "Segue", sender: nil) } // 検索ボタンを押した時に呼ばれる func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { self.view.endEditing(true) searchBar.showsCancelButton = true self.searchResult = memoText.filter { $0.lowercased().contains(searchBar.text!.lowercased()) } self.tableView.reloadData() } // キャンセルボタンを押した時に呼ばれる func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.showsCancelButton = false self.view.endEditing(true) searchBar.text = "" tableView.reloadData() } // 入力開始前に呼ばれる func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { searchBar.showsCancelButton = true return true } // ViewControllerへの引き継ぎ設定 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let vc = segue.destination as! ViewController // 新規以外 if(honIndex != -1) { vc.aDate = memoText[honIndex] } } }
試したこと
検索結果のCellをタップするとメモ一覧の一番上のメモの情報に遷移するのですが、
色々調べているとindexが関係しているかもと考え、現在indexについて調べているのですが解決には至っていない状況です。
ご教示頂けると幸いです。
補足情報(FW/ツールのバージョンなど)
XCode10
回答1件
あなたの回答
tips
プレビュー