我找到了下一个答案,使UIView的高度与其内容https://stackoverflow.com/a/39527226/7767664相匹配
我测试了它,它工作得很好(如果故事情节提要中的UIView高度大小大于或小于其内容,那么在运行时它会自动调整自身大小以匹配内容)。
但是,如果我使用UICollectionViewCell
而不是UIView
,那么没有什么变化,单元格的高度永远不会改变,它总是具有我们在故事板属性中的硬编码高度:
我还能做什么?
另外,我在UIControllerView中有2节(2列)。一行中的两个单元格应该具有相同的大小,即使它们的大小内容不同(类似于在使用RecyclerView和GridLayoutManager时在Android中本地实现的情况,非常容易)
更新
它适用于UIView
,因为我将它的top约束设置为Safe‘s’a top
我不能用UICollectionViewCell
更新2
看来我在这个答案上有了一些进展,https://stackoverflow.com/a/25896386/7767664
但是我需要的不是newFrame.size.width = CGFloat(ceilf(Float(size.width)))
,而是newFrame.size.height = CGFloat(ceilf(Float(size.height)))
当我们使用此解决方案时,不要向单元格底部添加任何约束,否则它将无法工作
使用此解决方案,我不能真正使用任何边距,否则在单元格底部某些部分变得不可见。
我想这个问题可以用https://stackoverflow.com/a/31279726/7767664来解决
发布于 2019-04-17 12:48:40
多亏了https://stackoverflow.com/a/25896386/7767664和https://stackoverflow.com/a/31279726/7767664,我解决了我的问题
我决定将一个包含所有需要的子视图的UIView
放到UICollecitonViewCell
中。
我将UIView
尾随、引导、顶部设置为ICollecitonViewCell
,但没有将其设置为单元格视图(您应该在UIView中使用最新的子视图,并连接它们的底部,而不是单元格视图)
然后,我将UIView的引用添加到我的自定义单元格类中,并使用它的高度表示单元格的高度:
public class MyCustomItemCell: UICollectionViewCell {
// other child views references ...
@IBOutlet weak var wrapperView: UIView! // view which contains your other views
//forces the system to do one layout pass
var isHeightCalculated: Bool = false
override public func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
//Exhibit A - We need to cache our calculation to prevent a crash.
if !isHeightCalculated {
setNeedsLayout()
layoutIfNeeded()
var newFrame = layoutAttributes.frame
newFrame.size.height = wrapperView.frame.height // use height of our UIView
layoutAttributes.frame = newFrame
isHeightCalculated = true
}
return layoutAttributes
}
}
发布于 2019-04-14 09:31:22
您可以尝试使用在您的collectionView扩展中或在您的本机collectionViewController类中调用的函数:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
//return something like the size. I write you an example how to use it.
// You can easily change the value according to your stuff contents height.
return CGSize(width: collectionView.frame.size.width/3, height: 100)
}
https://stackoverflow.com/questions/55676984
复制相似问题