質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
TableView

TableView(UITableView)とは、リスト形式で表示するコントロールで、ほとんどのアプリに使用されています。画面を「行」に分けて管理し、一般的には各行をタップした際に詳細画面に移動します。

iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

検索

検索は、あるデータの集まりの中から 目的のデータを見つけ出すことです。

Q&A

解決済

1回答

1681閲覧

[xcode]tableviewのタップした状態を保持したい

Jonny_dayo

総合スコア48

TableView

TableView(UITableView)とは、リスト形式で表示するコントロールで、ほとんどのアプリに使用されています。画面を「行」に分けて管理し、一般的には各行をタップした際に詳細画面に移動します。

iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

検索

検索は、あるデータの集まりの中から 目的のデータを見つけ出すことです。

0グッド

0クリップ

投稿2019/12/03 04:49

編集2019/12/03 06:03

状況

イメージ説明
選択すると暗くなるTableviewを使っているのですが、アクセサリーで画面移動したり、検索バーを押すと保持状態が消えてセルの色が白に戻ってしまいます…(中では押されている認識になっている)
また、検索バーを押している状態でアクセサリボタンを押すとエラーが出てしまいます…

エラーメッセージ

reason: 'Application tried to present modal view controller on itself. Presenting controller is <UISearchController: 0x7ffec9075200>.'

遷移先の画面
イメージ説明
青くなってる文字を変更して前の画面に戻る処理をする。

コード

override func viewDidLoad() { super.viewDidLoad() //searchControllerまとめ searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = (self as UISearchResultsUpdating) //位置を固定する searchController.hidesNavigationBarDuringPresentation = false searchController.searchBar.placeholder = "search" //フォーカス時に背景色を暗くするか? searchController.obscuresBackgroundDuringPresentation = false //サイズを調整 searchController.searchBar.sizeToFit() //tableViewのヘッダーにセット tableView.tableHeaderView = searchController.searchBar //Tableviewまとめ tableView.frame = tableViewContainer.bounds tableView.delegate = self tableView.dataSource = self tableView.allowsMultipleSelection = true tableViewContainer.addSubview(tableView) getData() NotificationCenter.default.addObserver(self, selector: #selector(cookingViewController.receivechange(_:)), name: Notification.Name("change"), object: nil) searchResults = recipedata.shared.nameArray.enumerated().map { $0.0 } } @objc func receivechange(_ notification: NSNotification) { let amountget = notification.userInfo!["amount"] as! String let priceget = notification.userInfo!["price"] as! String let cellget = notification.userInfo!["cellindex"] as! Int recipedata.shared.amountArray[cellget] = amountget recipedata.shared.priceArray[cellget] = priceget tableView.reloadData() } //画面をタップした時 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { baika.resignFirstResponder() genkaritsu.resignFirstResponder() } //文字が入力される度に呼ばれる func updateSearchResults(for searchController: UISearchController) { if searchController.searchBar.text! == ""{ searchResults = recipedata.shared.nameArray.enumerated().map { $0.0 } }else{ self.searchResults = recipedata.shared.nameArray.enumerated().filter({ // 大文字と小文字を区別せずに検索 $0.1.lowercased().contains(searchController.searchBar.text!.lowercased()) }).map({ $0.0 }) } self.view.endEditing(true) self.tableView.reloadData() } func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { searchController.dismiss(animated: true, completion: nil) celltaped = searchResults[indexPath.row] performSegue(withIdentifier: "edit", sender: nil) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchResults.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "Cell") cell.selectionStyle = .blue cell.textLabel?.text = recipedata.shared.nameArray[searchResults[indexPath.row]] cell.textLabel?.adjustsFontSizeToFitWidth = true cell.textLabel?.numberOfLines = 1 cell.detailTextLabel?.text = recipedata.shared.amountArray[searchResults[indexPath.row]] + recipedata.shared.taniArray[searchResults[indexPath.row]] + " " + recipedata.shared.priceArray[searchResults[indexPath.row]] + "円" cell.detailTextLabel?.adjustsFontSizeToFitWidth = true cell.detailTextLabel?.numberOfLines = 1 cell.accessoryType = .detailButton return cell } func getData(){ //省略 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at:indexPath) print("select - (indexPath)") cell?.isSelected = true //totalに入れる self.total += Float(recipedata.shared.priceArray[searchResults[indexPath.row]]) ?? 0 genkaTotal.text = String(self.total) //totalをラベルに反映させる selectedrecipe.append(indexPath.row) if kotei == "baika" { BaikaKotei() }else{ GenkaKotei() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "edit" { let nextVC = segue.destination as! CellViewController nextVC.namevalue = recipedata.shared.nameArray[celltaped] nextVC.categoryvalue = recipedata.shared.categoryArray[celltaped] nextVC.unitvalue = recipedata.shared.taniArray[celltaped] nextVC.amountvalue = recipedata.shared.amountArray[celltaped] nextVC.pricevalue = recipedata.shared.priceArray[celltaped] nextVC.cellindex = celltaped } } //2回目の選択時 func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { print("deselect - (indexPath)") let cell = tableView.cellForRow(at:indexPath) cell?.isSelected = false self.total -= Float(recipedata.shared.priceArray[searchResults[indexPath.row]]) ?? 0 genkaTotal.text = String(self.total) if let deselect = selectedrecipe.firstIndex(of: indexPath.row){ selectedrecipe.remove(at: deselect) } if kotei == "baika" { BaikaKotei() }else{ GenkaKotei() } } @IBAction func save(_ sender: Any) { searchController.dismiss(animated: true, completion: nil) var alertTextField: UITextField? let alert = UIAlertController( title: "レシピ名", message: "名前をつけて保存", preferredStyle: UIAlertController.Style.alert) alert.addTextField( configurationHandler: {(textField: UITextField!) in alertTextField = textField }) alert.addAction( UIAlertAction( title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil)) alert.addAction( UIAlertAction( title: "OK", style: UIAlertAction.Style.default) { _ in if let text = alertTextField?.text { var saver: [String] = UserDefaults.standard.array(forKey: "alert") as? [String] ?? [] saver.append(text) UserDefaults.standard.set(saver, forKey: "alert") var baikabox: [String] = UserDefaults.standard.array(forKey: "baikaB") as? [String] ?? [] baikabox.append(self.baika.text!) UserDefaults.standard.set(baikabox, forKey: "baikaB") //各々userdefaultに保管 var tap: [[Int]] = UserDefaults.standard.array(forKey: "tap") as? [[Int]] ?? [] tap.append(self.selectedrecipe) UserDefaults.standard.set(tap, forKey: "tap") } } ) self.present(alert, animated: true, completion: nil) } }

誰か助けてください(´;ω;`)

ツールのバージョン

Xcode : Version 11.2.1
Swift : Apple Swift version 5.1

追記

struct GoogleData: Decodable { let name: String let amount: String let unit: String let price: String let category: String private enum CodingKeys: String, CodingKey { case name case amount case unit case price case category } }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

Swift

1tableView cellForRowAt indexPath: IndexPath

のところで、他の

Swift

1cell.textLabel?.text = recipedata.shared.nameArray[searchResults[indexPath.row]] 2

と同じように、

Swift

1cell.isSelected = (true or falseの値を示す変数)

とisSelectedのBool型を設定してあげる必要があります。
なので、メモリ上にBool型の配列が必要になります。

本題とはそれますが、
データ構造が
値段 = [450, 300, 200, 100, 210]
品名 = [カレー, うどん, パン, ジュース, りんご]
となっておりますが、

商品1
name = "カレー"
category = 食べ物
price = 450
unit = "個"
のようにまとめた方が、わかりやすいのではないでしょうか?

下記のように、struct や enumをうまく組み合わせて実現できます。

Swift

1struct ItemData { 2 let name: String 3 let category: Category 4 let price: Int 5 let unit: String 6} 7 8enum Category { 9 case food 10 case drink 11} 12 13// データを流し込む時は下記のように 14let curry = ItemData(name: "カレー", category: .food, price: 450, unit: "袋")

投稿2019/12/03 05:51

編集2019/12/03 06:10
hameji

総合スコア1380

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Jonny_dayo

2019/12/03 06:07

回答ありがとうございます! cell.isSelected = true で試してみたところ、セルが一瞬灰色にぺろぺろするだけでした… ここに自分でifこうならTrue、って文に変えたらいける感じですかね…? データの構造についてもアドバイスありがとうございます! 一応追記のように別ファイルは作っているのですが、これとはまた別の話ですかね…?
hameji

2019/12/03 06:14

struct でデータを定義してあるなら、nameArrayやpriceArrayは不要になり、 var googleDataArray:[GoogleData] = *******などを宣言し、 その配列を利用して表示するになると思います。 また、次のNextViewへもそれぞれの要素を渡さずに、 GoogleData自体を渡せばいいのではないでしょうか?
Jonny_dayo

2019/12/03 06:16

なるほど確かに…( ゚д゚)ハッ! 面倒なことしてましたね… 今回の質問の件が解決したら書き直してみます!!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問