📖

【Swift】Searchable Table View【コピペコード】

2023/06/26に公開

スクリーンショット 2023-06-26 14.47.23.png

スクリーンショット 2023-06-26 14.47.53.png

【「ViewController」のコード】

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate {
    
    @IBOutlet var tableView: UITableView!
    @IBOutlet var textField:UITextField!
    
    var data = [String]()
    var filteredData = [String]()
    var filtered = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupData()
        tableView.delegate = self
        tableView.dataSource = self
        textField.delegate = self
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if let text = textField.text {
            filterText(text+string)
        }
        return true
    }
    
    func filterText(_ query:String) {
        filteredData.removeAll()
        for string in data {
            if string.lowercased().starts(with: query.lowercased()){
                filteredData.append(string)
            }
        }
        tableView.reloadData()
        filtered = true
    }
    
    private func setupData() {
        data.append("John")
        data.append("Abe")
        data.append("Jenny")
        data.append("Dan")
        data.append("Zach")
        data.append("Luke")
        data.append("Kevin")
        data.append("Briana")
        data.append("Melanie")
        data.append("Sarah")
        data.append("Shawn")
        data.append("Teri")
        data.append("Tom")
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if !filteredData.isEmpty {
            return filteredData.count
        }
        return filtered ? 0 : data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        if !filteredData.isEmpty {
            cell.textLabel?.text = filteredData[indexPath.row]
        } else {
            cell.textLabel?.text = data[indexPath.row]
        }
        return cell
    }
    
}

参考動画

Searchable Table View in Swift with Xcode 11 | iOS for Beginners
https://www.youtube.com/watch?v=-UQcifmThag&list=PL0aWQSxmqLHaVEtj4oUrBNFGhp8jcOFQd&index=3&t=10s

Discussion