Использование значений словаря для заполнения метки collectionView внутри tableView - PullRequest
0 голосов
/ 25 июня 2018

Итак, у меня есть collectionView внутри tableView. Я хотел бы использовать значения из моего массива, чтобы заполнить каждый текст метки внутри каждого collectionViewCell. Если я печатаю код ниже в collectionView cellForItemAt, я получаю следующее (см. Рисунок) (и, очевидно, индекс вне диапазона):

Print(array[indexPath.row].details.values)

Итак, используя пример с фотографии, как я могу получить следующее:

  • Внешняя таблицаViewCell (1)
    • CollectionViewCell (1)
      • этикетка - «1»
    • CollectionViewCell (2)
      • этикетка - "3"
    • CollectionViewCell (3)
      • этикетка - "5"
  • Внешняя таблицаViewCell (2)
    • CollectionViewCell (1)
      • этикетка - "7"

Также, как вы могли заметить, массив не в порядке, можно ли изменить порядок так:

["1": 1, "2": 3, "3": 5]

Любая помощь очень ценится, большое спасибо !!

Мой массив:

Data to display in label

Ответы [ 3 ]

0 голосов
/ 25 июня 2018

На основании ваших требований вот код

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    // Global Variable
    var tableView: UITableView!
    var dataArray = [["2": 3, "1": 1, "3": 5], ["1":7]]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView = UITableView(frame: self.view.bounds)
        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)

        tableView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
    }

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

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath as IndexPath) as! TableViewCell
     //   Passing data to cellection cell
            cell.cellData = dataArray[indexPath.row]
            cell.backgroundColor = UIColor.groupTableViewBackground
            return cell


    }

}

class TableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {

    var collectionView: UICollectionView!
    var cellData = [String: Int]()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.horizontal

        collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(CollectionCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
        collectionView.backgroundColor = UIColor.clear

        self.addSubview(collectionView)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    // MARK: UICollectionViewDataSource
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return cellData.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: CollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath as IndexPath) as! CollectionCell
        cell.textLable.text = String(Array(cellData)[indexPath.row].value) // Please check here is some casting 
        cell.backgroundColor = .black
        return cell
    }
}

class CollectionCell: UICollectionViewCell {

    let textLable: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        label.textColor = .white
        label.translatesAutoresizingMaskIntoConstraints = true
        label.textAlignment = .center
        return label
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLayout()
    }

    private func setupLayout() {
        addSubview(textLable)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Надеюсь, это решит вашу проблему.

Результат

enter image description here

0 голосов
/ 25 июня 2018

Если я правильно понял, у вас есть массив с этим, немного странным, форматом

array = [[["2": 3, "1": 1, "3": 5]], [["1":7]]]

Поскольку представление коллекции находится внутри представления таблицы, я предполагаю, что вы реализовали NSTableViewDataSource, и тогда вы можетесохраните текущую строку для табличного представления как свойство в tableView: viewFor: и, таким образом, получите массив для использования с этим свойством.Поскольку у вас есть массив внутри массива, нам нужно получить первый элемент в этом массиве, а затем отфильтровать этот элемент (словарь), где ключ соответствует текущему indexPath.row

let row = String(indexPath.row + 1)
let item = array[currentTableViewRow][0].filter {$0.key = row}
if !item.isEmpty {
     label.text = item.value
}
0 голосов
/ 25 июня 2018

Преобразовать в Массив С этим:

Array(array[indexPath.row].details.values)

И выведите это значение. Вы получите правильный массив в правильном порядке.

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

Спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...