我正在尝试创建一个动态UICollectionView,其单元格根据其中的文本自动调整大小。但由于某些原因,我的自定义UICollectionViewCell将不会扩展到全宽。我使用SnapKit作为AutoLayout,我的所有观点都是基于代码的;没有xib或故事板。这是我目前得到的调试视图:
我希望单元格扩展整个宽度和高度以适应任何内容。这是我的 UICollectionViewController
上的一个片段override func viewDidLoad() {
super.viewDidLoad()
self.title = "Home"
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: view.frame.width, height: view.frame.height)
layout.scrollDirection = .vertical
layout.estimatedItemSize = CGSize(width: 375, height: 250)
collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height), collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1)
collectionView.register(HomeCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
self.view.addSubview(collectionView)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
// Configure the cell
if let c = cell as? HomeCollectionViewCell {
c.contentView.frame = c.bounds
c.contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
configureCell(c, indexPath: indexPath)
}
return cell
}
func configureCell(_ cell: HomeCollectionViewCell, indexPath: IndexPath) {
cell.setText(withTitle: items[(indexPath as NSIndexPath).section].title)
}
这是我的自定义 UICollectionViewCell
的片段override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
self.contentView.translatesAutoresizingMaskIntoConstraints = true
self.contentView.bounds = CGRect(x: 0, y: 0, width: 99999, height: 99999)
createTitle()
}
private func createTitle() {
titleView = TTTAttributedLabel(frame: CGRect(x: 0, y: 0, width: contentView.frame.width, height: 56))
titleView.tag = 1
titleView.numberOfLines = 2
titleView.delegate = self
titleView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(titleView)
titleView.snp_updateConstraints(closure: {
make in
make.leading.trailing.equalTo(contentView).offset(10)
make.top.equalTo(contentView).offset(10)
make.bottom.equalTo(contentView).offset(-10)
})
}
func setText(withTitle title:String, paragraph: String, image: String) {
let titleAttributed = AttributedString(string: title, attributes: titleStringAttr)
titleView.attributedText = titleAttributed
titleView.sizeToFit()
}
我已经花了3天时间继续研究这个......任何建议都值得赞赏!
答案 0 :(得分:0)
嗯,这不是一个真正的解决方案,但是TTTAttributedLabel
做了一些黑魔法,导致AutoLayout无法正常工作。所以对我来说,我将TTTAttributedLabel
更改为UILabel
,它运行正常。
仅供参考我在SnapKit Github问题上发布了类似的问题;感谢robertjpayne提示(https://github.com/SnapKit/SnapKit/issues/261)