[英]Swift CollectionView changes size when imageview is inside
I have created a CollectionView with three items per row.我创建了一个 CollectionView,每行包含三个项目。 If my cell includes just a view its working really fine like the picture shows:
如果我的单元格只包含一个视图,它的工作非常好,如图所示:
But if I add an Imageview inside my view with equal constraints its going to look like this:但是,如果我在视图中添加一个 Imageview 并具有相同的约束,它将看起来像这样:
Here is my Code for my CollectionView:这是我的 CollectionView 的代码:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets.zero
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let yourWidth = collectionView.bounds.width/3.0
let yourHeight = yourWidth
return CGSize(width: yourWidth, height: yourHeight)
}
Seems like you are using a UICollectionViewFlowLayout
.好像您正在使用
UICollectionViewFlowLayout
。
This is not a bug or unexpected behavior.这不是错误或意外行为。 If there is something constrained to the edges of a cell's
contentView
, the layout will resize the cell to fit the contents.如果单元格的
contentView
边缘有某些限制,则布局将调整单元格的大小以适应内容。 Instead of constraining the image to the leading/trailing and top/bottom anchors, constrain its center to the cell's center, this way it will not affect the cell's size.不是将图像限制在前导/尾随和顶部/底部锚点,而是将其中心限制在单元格的中心,这样就不会影响单元格的大小。 You may leave
collectionView(_:layout:sizeForItemAt:)
as is.您可以按原样保留
collectionView(_:layout:sizeForItemAt:)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.