Как соответствовать горизонтальной ширине ячейки collectionView по размеру контента - PullRequest
0 голосов
/ 16 июня 2019

Я уже знаю некоторые связанные с этим вопросы, касающиеся этого, но я пробовал их раньше, но все еще не повезло.

Вот моя проблема на следующем скриншоте my current collectionView Мой текущий экран показывает фиксированный размер ячейки и отображает пустые места для меньшего содержимого и большего содержимого, проходящего по ячейке с точками.

я хотел как ниже enter image description here оно должно соответствовать ширине содержимого имени категории продукта.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if collectionView == self.catCollectionView{
        let catCell = collectionView.dequeueReusableCell(withReuseIdentifier: "catCell", for: indexPath)
            as! catCell

        DispatchQueue.main.async {
            catCell.configureCell()

            let catCountInt = self.catCountArray[indexPath.row]


            catCell.catCountLabel.text = String(catCountInt)
            catCell.catNameLabel.text = self.categoryNameArray[indexPath.row]
            catCell.catCountLabel.sizeToFit()
            catCell.catNameLabel.sizeToFit()

        }
        return catCell
 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let catCell = collectionView.dequeueReusableCell(withReuseIdentifier: "catCell", for: indexPath)
        as! catCell
    catCell.catNameLabel.text = self.categoryNameArray[indexPath.item]
    catCell.catNameLabel.sizeToFit()
     let labelWidth = catCell.catNameLabel.frame.width + 10
    print("frame width: \(labelWidth)")
    return CGSize(width: labelWidth, height: 21)
}

}

Может быть, я упускаю простую вещь здесь, но я не мог понять в данный момент. Пожалуйста, помогите мне и извините за мой странный английский.

Ответы [ 2 ]

2 голосов
/ 16 июня 2019

Давайте представим, что вы используете простой UICollectionViewCell подкласс с правильно установленными ограничениями в раскадровке (метка прикреплена ко всем четырем сторонам своего суперпредставления), например:

class CategoryCell: UICollectionViewCell {

    @IBOutlet var nameLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        layer.borderWidth = 1
    }

}

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

class CollectionViewController: UICollectionViewController {

    let categories = [
        "All Products",
        "Fresh",
        "Health & Beauty",
        "Beverages",
        "Home & life"
    ]

    private var flowLayout: UICollectionViewFlowLayout? {
        return collectionViewLayout as? UICollectionViewFlowLayout
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.backgroundColor = .white

        flowLayout?.sectionInset = .init(top: 15, left: 15, bottom: 15, right: 15)
        flowLayout?.sectionInsetReference = .fromSafeArea
        flowLayout?.estimatedItemSize = UICollectionViewFlowLayout.automaticSize

        DispatchQueue.main.async {
            self.flowLayout?.invalidateLayout()
        }
    }

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

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoryCell", for: indexPath) as! CategoryCell
        cell.nameLabel.text = categories[indexPath.row]
        return cell
    }

}

Результат:

result

1 голос
/ 16 июня 2019

Вместо dequeuing другого cell в collectionView(_:layout:sizeForItemAt:), вы можете просто вычислить width из categoryName, используя size(withAttributes:) для categoryName, т.е.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let text = self.categoryNameArray[indexPath.row] {
    let cellWidth = text.size(withAttributes:[.font: UIFont.systemFont(ofSize:14.0)]).width + 10.0
    return CGSize(width: cellWidth, height: 21.0)
}

в attributes, дайте все, что вы хотите, чтобы font. 1013 *.

...