效果:
思路:
先把UICollectionViewDelegate代理更换为UICollectionViewDelegateFlowLayout,然后实现func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize这个方法。该方法的作用系根据indexPath动态返回flowLayoutItem的CGSize。
那么重点来了,我们只针对文本类型来实现自适应宽度布局。既然为文本,那么基本上就可以利用文本的个数来决定UILabel的宽度,当然,中文文本基本上都可以认为是每个字宽度是固定的,但英文字母就不一定了。特殊表现为小写的i,l,大写的I,其宽度项比较其他字母而言窄了很多,那么就把它们特殊处理即可。
代码:
// 根据特殊性的i,l,I这三个字母,和一般字符来返回文本总宽度
public func getSpecialLetterWidth(_ letter: String) -> Int{
var letterCount: Int = letter.count
var width:Int = (letterCount * 15) + 15
while letterCount > 0 {
if letter.contains("i") || letter.contains("l") || letter.contains("I") {
width = width - 5
}
letterCount = letterCount - 1
}
return width
}
// 根据泛型集合内对象的长度进行动态设置FlowLayoutItem的CGSize,字符过长的文本直接让其宽度等于父布局即可
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if dataArray.name.count == 0 {
return CGSize(width: 0, height: 0)
}
if dataArray.name.count > 0 || dataArray[indexPath.row].name.count < 15 {
return CGSize(width: getSpecialLetterWidth(dataArray[indexPath.row].name), height: 30)
} else {
return CGSize(width: self.view.frame.width, height: 30)
}
}
private func installHistoryItemCollectionView(){
let collectionViewLayout = UICollectionViewFlowLayout()
collectionViewLayout.scrollDirection = .vertical
collectionViewLayout.minimumLineSpacing = 10
collectionViewLayout.itemSize = CGSize(width: 100, height: 50)
histoyItemCollectionView = UICollectionView(frame: self.frame, collectionViewLayout: collectionViewLayout)
histoyItemCollectionView.backgroundColor = UIColor.white
histoyItemCollectionView.register(HistoryCell.self, forCellWithReuseIdentifier: cellId.HISTORY_CELL)
self.addSubview(histoyItemCollectionView)
histoyItemCollectionView.snp.makeConstraints{ make in
make.width.equalTo(WIDTH - 40)
make.centerX.equalToSuperview()
make.top.equalTo(self.hotLabel.snp.bottom).offset(10)
make.bottom.equalTo(self.snp.bottom)
}
}