gpt4 book ai didi

ios - 如何在 swift 中使用 TextField 作为搜索栏?

转载 作者:行者123 更新时间:2023-11-30 11:05:53 26 4
gpt4 key购买 nike

我想将 textField 用作我的应用程序的 SearchBar。我按照youtube的教程进行操作我在 github 获得了它的源代码。但不幸的是它不适用于我的应用程序。我可以输入文本,但它不会过滤我输入的任何内容。我的代码如下供您引用。希望你能帮助我解决我的问题。非常感谢。

var participants: [Attendee]!
var filteredParticipants = [Attendee]()

override func viewDidLoad() {
super.viewDidLoad()
ParticipantTableView.delegate = self
ParticipantTableView.dataSource = self
searchAttendeesTextField.delegate = self
searchAttendeesTextField.addTarget(self, action: #selector(searchRecords(_ :)), for: .editingChanged)
}

//MARK:- UITextFieldDelegates

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
searchAttendeesTextField.resignFirstResponder()
return true
}

//MARK: - searchRecords

@objc func searchRecords(_ textField: UITextField) {
self.filteredParticipants.removeAll()
if textField.text?.count != 0 {

for participant in participants {
if let participantToSearch = textField.text{
let range = participant.lastName.lowercased().range(of: participantToSearch, options: .caseInsensitive, range: nil, locale: nil)
if range != nil {
self.filteredParticipants.append(participant)
}
}
}
}else {
for participant in participants {
filteredParticipants.append(participant)

}
}
ParticipantTableView.reloadData()

}

// MARK: TABLE VIEW DATA SOURCE

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


return participants.count
}



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "FoldingCell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "FoldingCell")
}
// cell?.textLabel?.text = filteredParticipants[indexPath.row]
return cell!
}

最佳答案

您的 ParticipantTableView 数据应使用 filteredParticipants 数组加载。

当您在 participants 数组中添加数据时,请同时在 filteredParticipants 数组中添加所有数据并重新加载 ParticipantTableView

然后在tableview dataSource方法中:

// MARK: TABLE VIEW DATA SOURCE

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


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "FoldingCell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "FoldingCell")
}

let attendeeSingleData = filteredParticipants[indexPath.row]
cell?.textLabel?.text = attendeeSingleData."The data that you want to add"
return cell!
}

Attendee 必须是您创建的结构或类,并且您必须根据字段添加数据。

不要从 participants 数组中删除数据,并像在 filteredParticipants 数组中所做的那样不断更改数据。

还有一件事,您的 tableView 名称是 ParticipantTableView,这不好。使用 lowerCamelCase 创建方法作为 participantTableView

要了解更多信息,您可以访问这个有用的 URL:

关于ios - 如何在 swift 中使用 TextField 作为搜索栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52732457/

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