首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UILabel SizeToFit不在UICollectionViewCell工作

UILabel SizeToFit不在UICollectionViewCell工作
EN

Stack Overflow用户
提问于 2022-03-16 05:23:27
回答 2查看 160关注 0票数 0

这是我的密码

代码语言:javascript
复制
        class DescriptionsViewController: UIViewController {
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            collectionView.delegate = self
            collectionView.dataSource = self
            let layout = TagFlowLayout()
            layout.estimatedItemSize = CGSize(width: 140, height: 40)
            collectionView.collectionViewLayout = layout
        }
    }

    class Row {
    var attributes = [UICollectionViewLayoutAttributes]()
    var spacing: CGFloat = 0

    init(spacing: CGFloat) {
        self.spacing = spacing
    }

    func add(attribute: UICollectionViewLayoutAttributes) {
        attributes.append(attribute)
    }

    func tagLayout(collectionViewWidth: CGFloat) {
        let padding = 10
        var offset = padding
        for attribute in attributes {
            attribute.frame.origin.x = CGFloat(offset)
            offset += Int(attribute.frame.width + spacing)
        }
    }
}

    class TagFlowLayout: UICollectionViewFlowLayout {
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let attributes = super.layoutAttributesForElements(in: rect) else {
            return nil
        }

        var rows = [Row]()
        var currentRowY: CGFloat = -1

        for attribute in attributes {
            if currentRowY != attribute.frame.origin.y {
                currentRowY = attribute.frame.origin.y
                rows.append(Row(spacing: 10))
            }
            rows.last?.add(attribute: attribute)
        }

        rows.forEach {
            $0.tagLayout(collectionViewWidth: collectionView?.frame.width ?? 0)
        }
        return rows.flatMap { $0.attributes }
    }
}

    extension DescriptionsViewController : UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return sourse.Ingredients.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell",for: indexPath) as? collectionViewCell else {
            
            return collectionViewCell()
        }
        
        cell.label.text = sourse.Ingredients[indexPath.row] //[indexPath.section]
        cell.label.preferredMaxLayoutWidth = collectionView.frame.width - 16
        cell.label.sizeToFit()
            
        return cell
    }
    
} // uicollectionViewDatasourse,UICollectionViewDelegate

    class collectionViewCell: UICollectionViewCell{
    
    @IBOutlet weak var label: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        self.layer.cornerRadius = label.frame.size.height / 2.0
        self.backgroundColor = #colorLiteral(red: 0.3647058904, green: 0.06666667014, blue: 0.9686274529, alpha: 1)
    }
} //UICollectionViewCell

文本将超出背景色,背景色不能适应文本长度

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-03-16 15:11:35

我添加了一些代码并回答了我的问题。

代码语言:javascript
复制
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: sourse.Ingredients[indexPath.item].size(withAttributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 17)]).width + 25, height: 30)
}

但是我认为这不是最好的答案,因为这个源代码可以检测到,他们只是添加了.width + 25

显然,这段代码并不是“动态的”,但它确实有效。

票数 0
EN

Stack Overflow用户

发布于 2022-03-16 06:22:36

这个问题存在于您的Xib约束中。当标签无法获得正确的框架时,sizeToFit将无法工作。

如果您想要标签适应您的文本长度,您可以尝试。

  • Snapkit

代码语言:javascript
复制
view.contentView.addSubview(label)
label.snp.makeConstraints {
 $0.centerY.equalToSuperview()
 $0.leading.trailing.equalToSuperview().inset(customOffset)
}

  • Xib

代码语言:javascript
复制
Juset set the same constraints, ___centeY, leading, trailing___, as by SnapKit(I am not familiar how to in Xib, so sorry about no cases)

  • 原始代码

这可能会有帮助

代码语言:javascript
复制
class tageCollectionViewCell: UICollectionViewCell{
    
    var label: UILabel!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupView() {
        label = UILabel()
        //... add your custom character
        contentView.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        let constraints = [
            label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
            label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
        ]
        NSLayoutConstraint.activate(constraints)
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71492124

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档