swift 自適應寬度的UICollectionViewCell實現

本來一開始使用的是TagListView(pod 'TagListView', '~> 1.4.1'),但是需要在固定寬度的情況下,實現左右滑動,于是,只覺得UICollectionView比較適合,只需要UICollectionViewCell寬度自適應就好了。

1.定義UICollectionViewFlowLayout和UICollectionView

let layout = UICollectionViewFlowLayout()
layout.estimatedItemSize = CGSize(width: 60, height: 22)
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 14
collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView!.backgroundColor = .white
collectionView!.showsVerticalScrollIndicator = false
collectionView!.showsHorizontalScrollIndicator = false
collectionView!.delegate = self
collectionView!.dataSource = self
collectionView!.register(TextLabelCell.self, forCellWithReuseIdentifier: "TextLabelCell")
self.view.addSubview(collectionView!)
collectionView!.snp.makeConstraints { ConstraintMaker in
      ConstraintMaker.left.equalTo(locationIcon.snp.right).offset(17)
      ConstraintMaker.top.equalTo(self.telLabel.snp.bottom).offset(10)
      ConstraintMaker.height.equalTo(22)
      ConstraintMaker.right.equalToSuperview().offset(-24)
 }

2.定義UICollectionViewCell

class TextLabelCell: UICollectionViewCell {
    
    let textLabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.contentView.layer.cornerRadius = 11
        self.contentView.layer.masksToBounds = true
        self.contentView.layer.borderWidth = 0.5
        self.contentView.layer.borderColor = UIColor(red: 0.31, green: 0.31, blue: 0.31, alpha: 1).cgColor
        
        textLabel.font = UIFont.YTFont(ofSize: 12)
        textLabel.textColor = UIColor(red: 0.31, green: 0.31, blue: 0.31, alpha: 1)
        textLabel.textAlignment = .center
        textLabel.frame = self.contentView.bounds
        self.contentView.addSubview(textLabel)
        
    }
    override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
        let size = self.textLabel.text?.size(withAttributes: [NSAttributedString.Key.font: UIFont.YTFont(ofSize: 12)]) ?? CGSize.zero
        let att = super.preferredLayoutAttributesFitting(layoutAttributes);
        att.frame = CGRect(x: 0, y: 0, width: size.width+28, height: 22)
        self.textLabel.frame = CGRect(x: 0, y: 0, width: att.frame.size.width, height: 22)
        return att;
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

3.基本就搞定了。主要是設置layout自適應,以及cell的寬度自適應就可以了。cell的自適應寬度需要重寫一個系統方法,上面的代碼已給出。我是需要左右滑動,你也可以使用上下滾動試試。

點擊下方贊賞,給作者一點鼓勵!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容