我有一个集合视图,其中包含动态高度的单元格(基于可能的多行标签和内部的文本视图),当我跨越多行时,它可以完美地适应高度。但是,当文本只有一个单词或没有覆盖整个屏幕宽度时,单元格的宽度与需要的一样宽,从而导致单元格彼此相邻而不是彼此下方。
但是,我希望单元格位于彼此下方,想想 Instagram 或 Twitter 的视图。我显然需要为单元格设置一个宽度约束,使其等于屏幕的整个宽度,但我似乎无法找到如何做到这一点。
我在 AppDelegate 中使用 FlowLayout 和估计的ItemSize:
let layout = UICollectionViewFlowLayout()
window?.rootViewController = UINavigationController(rootViewController: HomeController(collectionViewLayout: layout))
layout.estimatedItemSize = CGSize(width: 414, height: 150)
我还在 viewDidLoad 中为 collectionView 设置了约束,因此 collectionView 占据了屏幕的整个宽度和高度:
collectionView?.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
collectionView?.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
collectionView?.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
collectionView?.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
我对标签和文本视图的约束看起来像这样,还允许宽度采用所需的大小(所以它不是固定的):
// vertical constraints usernameLabel & commentTextView
addConstraintsWithFormat(format: "V:|-16-[v0]-2-[v1]-16-|", views: usernameLabel, commentTextView)
// horizontal constraints usernameLabel
addConstraintsWithFormat(format: "H:|-16-[v0]-16-|", views: usernameLabel)
// horizontal constraints commentTextView
addConstraintsWithFormat(format: "H:|-16-[v0]-16-|", views: commentTextView)
在我看来,所有这些对于完成这项工作至关重要。但是,在我看来,我还没有设置宽度约束来完成这项工作。我试图在 collectionView 上添加一个 widthAnchor(等于 view.widthAnchor),这不起作用:
collectionView?.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
我也尝试在 sizeForItemAt 方法中设置宽度,但这也不起作用:
return CGSize(width: view.frame.width, height: 100)
现在,我正在检查宽度以查看哪里出了问题,但我得到了我需要的结果,我认为:
print("collectionView width: ", collectionView?.frame.size.width)
print("collectionView height: ", collectionView?.frame.size.height)
print("screen width: ", UIScreen.main.bounds.width)
print("screen height: ", UIScreen.main.bounds.height)
结果是:
collectionView width: Optional(414.0)
collectionView height: Optional(736.0)
screen width: 414.0
screen height: 736.0
我对如何前进没有想法。我浏览过的与此问题相关的所有文章或帖子要么明确计算高度,要么使用我上面提到的两种解决方案。
关于我做错了什么的任何想法?