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的自适应宽度需要重写一个系统方法,上面的代码已给出。我是需要左右滑动,你也可以使用上下滚动试试。

点击下方赞赏,给作者一点鼓励!

你可能感兴趣的:(swift 自适应宽度的UICollectionViewCell实现)