Как использовать TextField в качестве searchBar в Swift? - PullRequest
0 голосов
/ 10 октября 2018

Я хочу использовать 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!
}

Ответы [ 2 ]

0 голосов
/ 10 октября 2018

Ваши данные 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:

0 голосов
/ 10 октября 2018

Здравствуйте, вам нужно использовать методы TextField Delegate для него.Вы можете использовать это

func textFieldDidBeginEditing(_ textField: UITextField) {
    //you will get here updated entered text
    print("TextField did begin editing method called", textField.text)
}
...