LoginSignup
0
0

More than 5 years have passed since last update.

質問です。

Posted at

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate{

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!

 let PPAP:[String] = ["平泉", "日光東照宮", "国立西洋美術館", "富士山", "京都"]

var searchResults:[String] = []

override func viewDidLoad() {
super.viewDidLoad()

tableView.register(UITableViewCell.self, forCellReuseIdentifier: "PPAP")
tableView.dataSource = self
tableView.delegate = self
self.view.addSubview(tableView)

searchBar.delegate = self
searchBar.searchBarStyle = UISearchBar.Style.default
searchBar.showsSearchResultsButton = false
searchBar.placeholder = "検索"
searchBar.setValue("キャンセル", forKey: "_cancelButtonText")
searchBar.tintColor = UIColor.red

tableView.tableHeaderView = searchBar

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

// lines of cells
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchBar.text != "" {
return searchResults.count
} else {
return PPAP.count
}
}
// add texts of cells
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PPAP",for: indexPath as IndexPath)
if searchBar.text != "" {
cell.textLabel!.text = "(searchResults[indexPath.row])"
} else {
cell.textLabel!.text = "(PPAP[indexPath.row])"
}

return cell

}

/// セル選択時(UITableViewDataSource optional)
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

}

// 検索ボタンが押された時に呼ばれる
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.view.endEditing(true)
searchBar.showsCancelButton = true
self.searchResults = PPAP.filter{
$0.lowercased().contains(searchBar.text!.lowercased())
}
self.tableView.reloadData()
}

// キャンセルボタンが押された時に呼ばれる
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = false
self.view.endEditing(true)
searchBar.text = ""
self.tableView.reloadData()
}

// テキストフィールド入力開始前に呼ばれる
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.showsCancelButton = true
return true
}
}

上記コードで、セクションを複数にしたいです。
どうすればいいですか?

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0