словарь для источника данных tableView - PullRequest
0 голосов
/ 19 января 2020

Я пытаюсь использовать словарь для источника данных tableView. Я получаю объект из базы данных, который содержит ключ и массив значений, поэтому [String: [String]]

    var requestedList = [String]()
    var keyArr = [String]()
    var requestedDictionary = [String: [String]]()

    let tQuery = PFQuery(className: "MyClass")
        tQuery.whereKey("username", equalTo: PFUser.current()?.username as Any)
        tQuery.selectKeys(["descContent", "header"])
        do {
            let returnedObjects = try tQuery.findObjects()
            for object in returnedObjects {
                let header = object["header"] as! String
                keyArr.append(header)
                if let arr = object["descContent"] as! [String]? {
                    requestedDictionary[header] = arr
                    requestedList += arr
                }
            }
        } catch {
        }

Кажется, я не могу правильно соотнести значения со строками tableView, однако мне предложили использовать массив для хранения значений, что я и сделал с keyArr. Моя проблема заключается в том, как мне получить доступ к содержимому ключей и соответствующих значений в методах источника данных ?? Это то, что у меня есть, но я не смог связать ключи и значения соответственно

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

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

        cell.descLbl.text = "Your ticket has been requested by \(requestedList[indexPath.row])"
        cell.refLbl.text = "for: \(keyArr[indexPath.row])"

        cell.leftBtn.tag = (indexPath.section * 100) + indexPath.row
        cell.leftBtn.addTarget(self, action: #selector(leftClick(sender:)), for: .touchUpInside)
        cell.rightBtn.tag = (indexPath.section * 100) + indexPath.row
        cell.rightBtn.addTarget(self, action: #selector(rightClick(sender:)), for: .touchUpInside)

        return cell
    }

1 Ответ

1 голос
/ 19 января 2020

Вы можете превратить словарь в tableView представимых данных таким образом.

let requestedDictionary:[String: [String]] = [
    "Key-1":["Value-1","Value-2","Value-3","Value-4"],
    "Key-A":["Value-X","Value-Y","Value-Z"],
    "Key-a":["Value-x","Value-y"],
]
lazy var data:[(key:String,values:[String])] = requestedDictionary.compactMap({(key:$0,values:$1)})

func numberOfSections(in tableView: UITableView) -> Int {
    data.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data[section].values.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.text = data[indexPath.section].values[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return data[section].key
}

Надеюсь, это поможет.

...