我正在尝试将UICollectionView设置为水平菜单,在另一个UICollectionView之上(但这是无关紧要的) .
现在我的细胞基本上由标签组成,你可以想象不同的宽度 . 所以我尝试用这个函数计算大小:
func getSizeOfCell(string: String, font: UIFont) -> CGSize {
let textString = string as NSString
let textAttributes = [NSFontAttributeName: font]
let size = textString.boundingRect(with: CGSize(width: 320, height: 2000), options: .usesLineFragmentOrigin, attributes: textAttributes, context: nil)
return CGSize(width: size.width, height: size.height)
}
你可以看到哪个不是真的做得很好:
当字符串很长时,包含标签的视图太大 .
我有点被迫给sizeForItem一个CGSize吧?我不能只是让我的CollectionView根据它包含的标签自动获取单元格的大小?
[编辑]所以这是我的细胞类:
class MenuCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
override var isSelected: Bool {
didSet {
labelTitre.textColor = isSelected ? UIColor.black : .lightGray
}
}
let labelTitre : UILabel = {
let label = UILabel()
label.textColor = .gray
return label
}()
func setupViews() {
backgroundColor = UIColor.white
addSubview(labelTitre)
addConstraintsWithFormat(format: "H:[v0]", views: labelTitre)
addConstraintsWithFormat(format: "V:[v0]", views: labelTitre)
addConstraint(NSLayoutConstraint(item: labelTitre, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: labelTitre, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
这是我构建我的collectionView的方法:
lazy var customCollectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.estimatedItemSize = CGSize(width: 60, height: 30)
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.collectionViewLayout = layout
cv.backgroundColor = UIColor.white
cv.dataSource = self
cv.delegate = self
return cv
}()
同样在我的viewController的viewDidLoad()中:
customCollectionView.register(MenuCell.self, forCellWithReuseIdentifier: cellId)
addSubview(customCollectionView)
addConstraintsWithFormat(format: "V:|[v0]|", views: customCollectionView)
addConstraintsWithFormat(format: "H:|[v0]|", views: customCollectionView)
1 回答
您可以使用约束来使单元格“自动调整大小”,并且您不必手动计算文本/标签大小 .
试一试 . 当然,它需要修改以满足您的需求,但应该给您一些工作( Edit :我更新了我的代码以更接近您的方法):
Edit:
以下是我的代码结果的上限:
并且代码的结果上限 - 编辑了一行:
在您的单元格代码中,更改:
至: