Поиск элемента пользовательского UITableCell и фильтрация с помощью Swift 4 - PullRequest
0 голосов
/ 28 августа 2018

Я пытаюсь реализовать функцию поиска в моем UITableViewController. Поэтому я добавил контроллер поиска поверх ячейки внутри UITableView.

Я сделал это UISearchBarDelegate с помощью моего TableViewController.

Вот мой код для фильтрации поискового текста:

// This method updates filteredData based on the text in the Search Box
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    // When there is no text, filteredData is the same as the original data
    // When user has entered text into the search box
    // Use the filter method to iterate over all items in the data array
    // For each item, return true if the item should be included and false if the
    // item should NOT be included
    filteredData = searchText.isEmpty ? OrderDetailsTabBarViewController.orderDetailsList : OrderDetailsTabBarViewController.orderDetailsList.filter { (item: OrderBookedSetterGetter) -> Bool in
        // If dataItem matches the searchText, return true to include it
        return item.BookedOrderId(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil
    }

    tableView.reloadData()
}

Но это показывает ошибку Невозможно вызвать значение нефункционального типа 'Int' в return item.BookedOrderId (of: searchText, options: .caseInsensitive, range: nil, locale: ноль)! = ноль строка.

BookedOrderId - это Int

Может ли кто-нибудь помочь мне с этим. Я застрял здесь и не могу ничего найти.

Кроме того, я следовал этому уроку:

Ссылка здесь

Спасибо.

Ответы [ 2 ]

0 голосов
/ 28 августа 2018

Это то, что я сделал, и это работает!

Используйте копию ваших оригинальных данных и используйте их для просмотра контроллера

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        // When there is no text, filteredData is the same as the original data
        // When user has entered text into the search box
        // Use the filter method to iterate over all items in the data array
        // For each item, return true if the item should be included and false if the
        // item should NOT be included


            self.searchBar.showsCancelButton = true

            self.copied_order_Canceled_DetailList = []
            for item in self.order_Canceled_DetailList {
            if String(item.orderId).localizedCaseInsensitiveContains(searchText) != false{
               self.copied_order_Canceled_DetailList.append(item))
            } else {

                }
            }

            self.tableview.reloadData()
            if searchText == "" {
                self.copied_order_Canceled_DetailList = self.order_Canceled_DetailList
                self.tableview.reloadData()
            }
        }

Это должно работать.

0 голосов
/ 28 августа 2018

Вы, вероятно, имеете в виду range(of.... Чтобы использовать это, вы должны конвертировать Int в String

filteredData = searchText.isEmpty ? OrderDetailsTabBarViewController.orderDetailsList : OrderDetailsTabBarViewController.orderDetailsList.filter { (item: OrderBookedSetterGetter) -> Bool in
    // If dataItem matches the searchText, return true to include it
    let stringOrderId = String(item.BookedOrderId)
    return stringOrderId.range(of: searchText, options: .caseInsensitive) != nil
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...