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

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

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

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

Xcode

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

Swift

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

検索

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

Q&A

解決済

2回答

369閲覧

swift section分けされたtableviewにsearchBarの実装

Larry

総合スコア28

TableView

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

Xcode

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

Swift

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

検索

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

0グッド

0クリップ

投稿2019/03/05 09:17

編集2019/03/06 07:50

前提・実現したいこと

swift4.2.1
Xcode10.1

section分けされたtableviewにsearchBarを実装したいです。

以下のサイトを参考にしました
https://daisa-n.com/blog/ios-swift-foldingtableview/

発生している問題・エラーメッセージ

以下のコードですと下の写真のように検索した際にitems1のデータしか表示されないようになっています。
func searchBarとfunc tableViewのところをどうにかすればいけるのかなと思っていますが, なに分初心者なものでいまいちよくわからないです。ご教授いただければ幸いです。よろしくお願いします。
イメージ説明

該当のソースコード

import UIKit class ViewController:UIViewController,UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate { @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var tableView: UITableView! var searchActive : Bool = false var items1: NSMutableArray = ["ねずみ", "うし", "とら", "うさぎ", "りゅう"] var items2: NSMutableArray = ["へび", "うま","ひつじ","さる","とり","いぬ","いのしし","ねこ","しまうま"] var items3: NSMutableArray = ["やぎ","くま","しろくま","こぶら","ごりら","ぶた","ぞう","おおかみ"] var section1: Dictionary = [String:NSMutableArray]() var section2: Dictionary = [String:NSMutableArray]() var section3: Dictionary = [String:NSMutableArray]() //全てのセクションタイトルとセルの中身を辞書形式で格納 var sections: Array = [Dictionary<String,NSMutableArray>]() var filtered:[String] = [] override func viewDidLoad() { super.viewDidLoad() // セクションのタイトルとデータの配列を設定する。//辞書 section1 = ["あ":items1] section2 = ["か":items2] section3 = ["さ":items3] // セクションを配列に設定する。 sections.append(section1) sections.append(section2) sections.append(section3) //デリゲート設定 tableView.delegate = self tableView.dataSource = self searchBar.delegate = self } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchActive = true; } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { searchActive = false; } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchActive = false; } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchActive = false; } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { filtered = items1.filter({ (text) -> Bool in let tmp: NSString = text as! NSString let range = tmp.range(of: searchText) return range.location != NSNotFound }) as! [String] if(filtered.count == 0){ searchActive = false; } else { searchActive = true; } self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //セクションの数返す func numberOfSections(in tableView: UITableView) -> Int { return sections.count } // セクションのタイトルを返す。 func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var title = "" for (key) in sections[section].keys { title = key } return title } //セルの数をばっこり返す//セクションごとにデータ(セル)要素数を入れるメソッド func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if(searchActive) { return filtered.count } return items1.count; } //セルを返す//表示する func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell",for:indexPath as IndexPath) if(searchActive){ cell.textLabel?.text = filtered[indexPath.row] } else { cell.textLabel?.text = items1[indexPath.row] as? String; } return cell; } }

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

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

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

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

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

fuzzball

2019/03/06 07:26

コードは ``` で囲って下さい。
guest

回答2

0

ベストアンサー

データの持ち方がおかしいです。
セクションタイトル(あ、か、さ)も値なのに、それをキーにしているのが間違いです。

タプルを使った例を書くと、

swift

1let sections = [ 2 (title: "あ", items: ["ねずみ", "うし", "とら", "うさぎ", "りゅう"]), 3 (title: "か", items: ["へび", "うま","ひつじ","さる","とり","いぬ","いのしし","ねこ","しまうま"]), 4 (title: "さ", items: ["やぎ","くま","しろくま","こぶら","ごりら","ぶた","ぞう","おおかみ"]), 5 ] 6print(sections[0].title) //=> あ 7print(sections[1].items) //=> ["へび", "うま", "ひつじ", "さる", "とり", "いぬ", "いのしし", "ねこ", "しまうま"] 8print(sections[2].items[5]) //=> ぶた

となります。

投稿2019/03/06 07:48

編集2019/03/06 07:49
fuzzball

総合スコア16731

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

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

0

cellForRowAtでcellを作成するとき、item1しか参照していません。(コード内の//★)
indexPath.sectionでsection番号がわかるので、section番号に応じてitem1/item2/item3を切り替える必要があります。

//セルを返す//表示する func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell",for:indexPath as IndexPath) if(searchActive){ cell.textLabel?.text = filtered[indexPath.row] } else { cell.textLabel?.text = items1[indexPath.row] as? String;//★ } return cell; }

投稿2019/03/05 10:19

dsuzuki

総合スコア1682

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

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

Larry

2019/03/05 12:44

ご回答ありがとうございます。ご指摘に従い、switch文を利用して、各セクションごとに対応するセルを表示させることができました。しかし、検索をかけた際の処理がわかりません。例えば"ねずみ"と検索すると、全てのセクションにねずみのセルが出てきてしまいます。 おそらく func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { filtered = items1.filter({ (text) -> Bool in let tmp: NSString = text as! NSString let range = tmp.range(of: searchText) return range.location != NSNotFound }) as! [String] if(filtered.count == 0){ searchActive = false; } else { searchActive = true; } self.tableView.reloadData() } の部分のコードがitems1のみになっているからだと思うのですが、どのようにすべてのitemsを参照させるのかがわかりません。教えていただければ幸いです。よろしくお願いします。
dsuzuki

2019/03/06 06:57

filteredにitems1の検索結果を格納するのなら、 items2の検索結果、items3の検索結果を格納する[String]を用意すればいいのではないでしょうか。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問