Swift实现自动计算collectionView的item的大
2018-06-05 本文已影响9人
闲云悠鹤蝶恋舞
实现步骤:
1)遵守代理UICollectionViewDelegateFlowLayout
2)实现UICollectionViewDelegateFlowLayout代理
在下面的代理方法中实现自动计算文本宽度即可!!!
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let str = titleArr[indexPath.row]
let dic = [NSAttributedStringKey.font:UIFont.systemFont(ofSize: 13.0)]
let size = CGSize(width: CGFloat(MAXFLOAT), height: 30)
let width = str.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic, context: nil).size.width
return CGSize(width: width+20, height: 30)
}