我正在尝试创建一个动态的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天的时间进行这项工作。.任何建议表示赞赏!
最佳答案
好吧,这并不是真正的解决方案,但是TTTAttributedLabel
做了一些黑魔法,使AutoLayout无法正常工作。因此,对我来说,我将TTTAttributedLabel
更改为UILabel
,并且效果很好。
仅供参考,我在SnapKit Github问题上发布了类似的问题;归功于robertjpayne那里的提示(https://github.com/SnapKit/SnapKit/issues/261)
关于ios - 具有AutoLayout的UICollectionViewCell在iOS 10中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38595602/