Как сделать динамические ячейки в CollectionView?


#1

Подскажите плз, как сделать так, как на картинке?

у меня сейчас так:
Не пойму почему не берёт intrinsicContentSize и как сделать, чтобы они так же обтекались?

21

extension FilterProgramsViewController: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FilterCollectionViewCell", for: indexPath) as! FilterCollectionViewCell
        let width = cell.tagNameLabel.intrinsicContentSize.width
        let height = CGFloat(44)
        return CGSize(width: width, height: height)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 15
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
}

#2

Как-то так. Только ппоменяйте на свой шрифт и если нужно, добавьте к полученной ширине дополнительные отступы

func getTextWidth(_ string: String): CGFloat {
    let rect = string.boundingRectWithSize(constraintSize, options: NSStringDrawingOptions.UsesFontLeading, 
    attributes: [NSFontAttributeName : UIFont.systemFontOfSize(17)], context: nil)
    return rect.size.width
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let text = textArray[indexPath.row]
        let width = getTextWidth(text)
        let height = CGFloat(44)
        return CGSize(width: width, height: height)
    }

#3

спс, сработало, но чуть чуть не так)

func sizeOfString (string: String) -> CGSize {
    return NSString(string: string).boundingRect(with: CGSize(width: 0, height: 0),
                                                 options: .usesFontLeading,
                                                 attributes: [.font: UIFont.systemFont(ofSize: 32)],
                                                 context: nil).size
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let text = allCategories[indexPath.row].rawValue
    return sizeOfString(string: text)
}

38

Так я не понял, как сделать чтобы они обтекались.
Ещё если поствать размер 16, который мне нужен, то текст будет обрезаться тремя точками.

И что значит параметр with в boundingRect, как только я его не крутил всё одно и тоже, не меняется.

Ячейку делаю через xib