Как получить значение индекса массива в словаре для заполнения таблицы - PullRequest
0 голосов
/ 09 апреля 2020

У меня есть теги продукта, хранящиеся в следующей переменной:

var productTags : [String : [String]] = [:]

У меня также есть строка поиска для моего tableView, где я заполняю следующую переменную на основе того, что пользователь ищет из productTags:

var searchResults: [String : [String]] = [:]

Таким образом, содержимое этих двух переменных будет примерно таким:

productTags = [ product1 : [tag1, tag2, tag3, tag4],
                product2 : [tag1, tag2, tag3, tag4, tag 5], 
                product3 : [tag1, tag2, tag3]
              ] 
// similar for the searchResults depending on the search

Теперь я хотел бы заполнить только tag1 каждого продукта в tableView , Как мне go сделать это?

func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    return //what should I be returning here? 
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: Identifiers.HomeSearchCell, for: indexPath) as! HomeSearchCell

    cell.productName?.text = //how can I populate the "tag1" of the product in here? so the label shows the tag1 as the search result

    return cell
}

Я также хочу убедиться, что могу отследить, какой именно тег нажимает пользователь, чтобы я мог отследить тег до идентификатора продукта. Например, если вы ищете tag1 из product2, а затем вы увидите tag1 в результате поиска в представлении таблицы и щелкните по нему; как я могу получить идентификатор продукта, который в данном случае равен product2 из выбранной строки?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// what should I put here to get the productID of the tag/row selected by the user from the searchresults? 
    }

РЕДАКТИРОВАТЬ: Вот как я заполняю productTags:

db.collection(DatabaseRef.searchTags).document(DatabaseRef.productTags).getDocument { snapshot, error in

            guard error == nil, let snapshot = snapshot else {
                return
            }

            let data = snapshot.data()!

            for (key, _) in data {

                let productTags = data["\(key)"] as? [Any]

                if let maxIndex = productTags?.count {

                    for index in 0..<maxIndex {
                        if let tag = productTags![index] as? String, tag != "" {

                            if self.productTags[key] == nil {
                                self.productTags[key] = []
                                self.productTags[key]?.append(tag)
                            } else {
                                self.productTags[key]?.append(tag)
                            }
                        }
                    }

                }
            }
        }

, и именно так я фильтрую свой productTags, чтобы заполнить searchResults:

searchResults = productTags.filter({ (productTags) -> Bool in
            if let name = productTags.value as? [String] {
                for tag in name {
                    let isMatch = tag.localizedCaseInsensitiveContains(SearchText)
                    return isMatch
                }
            }
            return false
        })

1 Ответ

1 голос
/ 09 апреля 2020

TableViews работают лучше всего при работе с массивами. Если возможно, я бы превратил словарь в массив Dictionary<String:[String]>. Так это будет выглядеть примерно так:

var productTags: [[String: [String]]] = [
    [product1: [tag1, tag2, tag3, tag4]],
    [product2 : [tag1, tag2, tag3, tag4, tag5]],
    [product3 : [tag1, tag2, tag3]]
]

Тогда оттуда вы можете вернуть количество словарей продуктов в массиве

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

         return productTags.count 
    }

И оттуда вы можете получить доступ к productTagDictionaries по indexPath. .row

 let productTags = productTags[indexPath.row].values.first
 cell.productName?.text = productTags?.first
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...