gpt4 book ai didi

ios - 使用自定义单元格将搜索栏实现到 uitableview

转载 作者:行者123 更新时间:2023-11-28 07:24:50 25 4
gpt4 key购买 nike

我创建了一个带有自定义单元格的表格 View ,现在我正在努力添加一个搜索栏。

import UIKit

class ViewController: UIViewController, UITableViewDataSource {

var SVGdata = [SVG]()

override func viewDidLoad() {
super.viewDidLoad()

}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

createSVGdata()
}

// Create movies data
func createSVGdata() {
SVGdata.append(SVG(SVGArtikel: "Art. 1", SVGGesetzestext: "Das darfst du nicht tun"))
SVGdata.append(SVG(SVGArtikel: "Art. 2", SVGGesetzestext: "Und das erst recht nicht"))

}

// TableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return SVGdata.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SVGCell", for: indexPath)

let sVG = SVGdata[indexPath.row]
if let SVGCell = cell as? SVGCell {
SVGCell.setSVG(sVG)
}

return cell
}

有数以千计的视频如何在一个简单的数组中进行搜索。但不是我的解决方案。

最佳答案

您可以使用 UISearchBar 执行此操作。首先在您的 tableView 所在的同一个 viewController 的 Storyboard上添加一个 UISearchBar(在 table view 顶部添加搜索栏,如 iOS。联系应用程序)然后添加如下代码的引用:

@IBOutlet weak var searchBar: UISearchBar!

然后在 viewDidLoad 中添加委托(delegate):

self.searchBar.delegate = self

我有两个 dataArray allData,filteredData。在 allData 中,我保留了表的所有数据(没有在任何地方更改它)和 filteredData 用于获取过滤结果。因此,在将数据填充到 allData 之后,我完成了 from (viewWillAppear):

filteredData = allData

因此,所有 tableView 委托(delegate),数据源都使用 filteredData。
然后扩展您的 viewController(扩展不是强制性的)以符合 UISearchBarDelegate :

当您对 tableView 使用 SVGdata(我使用 filteredData)时,过滤后您必须在重新加载表格之前将所有过滤数据放入 SVGdata。

extension YourViewController: UISearchBarDelegate{
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
// searchText will contain user input
// in allData I have kept all data of the table
// filteredData used to get the filtered result
if (searchText == ""){
filteredData = allData
}
else{
filteredData = []
// you can do any kind of filtering here based on user input
filteredData = allData.filter{
$0.cName.lowercased().contains(searchText.lowercased())
}
}
// lastly you need to update tableView using filteredData so that the filtered rows are only shown
//As you use SVGdata for tableView, after filtering you have to put all filtered data into SVGdata before reloading the table.
self.tableView.reloadData()
}
}

关于ios - 使用自定义单元格将搜索栏实现到 uitableview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56899795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com