ios - 具有固定高度/宽度的自定大小的 UICollectionViewCell

标签 ios swift uicollectionviewcell

所以我有这个 Collection View ,其中包含混合的自身大小的单元格和固定大小的单元格。 它适用于 self 调整大小的 self ,但我无法让固定的保持固定大小。这是我所做的:

// I have a viewContainer inside the cell's contentView
let viewContainer = UIView()
viewContainer.backgroundColor = .red
viewContainer.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(viewContainer)

// This viewContainer has a fixed width/height and is achored to the top, left, right, bottom of the contentView
viewContainer.topAnchor.constraint(equalTo: self.contentView.topAnchor).isActive = true
viewContainer.leftAnchor.constraint(equalTo: self.contentView.leftAnchor).isActive = true
viewContainer.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor).isActive = true
viewContainer.rightAnchor.constraint(equalTo: self.contentView.rightAnchor).isActive = true
viewContainer.heightAnchor.constraint(equalToConstant: FIXED_HEIGHT).isActive = true
viewContainer.widthAnchor.constraint(equalToConstant: FIXED_WIDTH).isActive = true

// Then I got my ImageView (property of my cell), as a viewContainer subview
self.photoImageView.translatesAutoresizingMaskIntoConstraints = false
self.photoImageView.contentMode = .scaleAspectFill
viewContainer.addSubview(self.photoImageView)

// It has a fixed width/height and is achored to the top, left, right, bottom of the viewContainer
self.photoImageView.topAnchor.constraint(equalTo: viewContainer.topAnchor).isActive = true
self.photoImageView.leftAnchor.constraint(equalTo: viewContainer.leftAnchor).isActive = true
self.photoImageView.bottomAnchor.constraint(equalTo: viewContainer.bottomAnchor).isActive = true
self.photoImageView.rightAnchor.constraint(equalTo: viewContainer.rightAnchor).isActive = true
self.photoImageView.heightAnchor.constraint(equalToConstant: FIXED_HEIGHT).isActive = true
self.photoImageView.widthAnchor.constraint(equalToConstant: FIXED_WIDTH).isActive = true

不知何故,当我有图像时(来自图像选择器,在委托(delegate)中有一个简单的重新加载数据),单元格被调整大小,图像的大小:

unwanted self sized cell

但是在 collectionView 上快速上下滚动后,它看起来不错:

right sized cell

我厌倦了在 heightAnchor 和 withAnchor UILayoutPriority(999.0) 上添加高优先级,但它似乎没有帮助。我找不到一种方法来调整该单元格的大小以及我想要的单元格图像。我觉得它与 ImageView 中的图像有关,但我不明白它是如何以及为什么这样做的。 谁能帮我解决这个问题?

预先感谢您的回答。

编辑: 我还尝试创建一个 UIImageView 子类并覆盖 intrinsicContentSize 以使其返回我想要的大小,但仍然没有成功:/

最佳答案

不确定这是最好的解决方案,但我最终以 999 优先级在单元格的 contentView 上添加了宽度/高度限制。我仍然有自动布局警告。但它似乎工作“还行”。

关于ios - 具有固定高度/宽度的自定大小的 UICollectionViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56686223/

相关文章:

ios - Objective c 用于内存管理的ARC AC 算法,这是垃圾收集吗?

ios:在 TextView 中编辑时,键盘返回键不起作用

ios - UITableViewCells iOS 中的白色区域

ios - 当CollectionView只有一个项目时,如何使垂直uiCollectionViewCell变为左侧

ios - iPhone 上的状态栏时钟已被截断

ios - 根据屏幕大小快速更改按钮高度

c# - 创建一个与 iPhone 进行 JSON 通信的 ASP.NET Web 服务

ios - 仅适合标签的高度

ios - UICollectionView indexPath.row 或项目,项目不稳定,跳来跳去

iphone - 如何自定义 UICollectionViewCell 子类的选择状态?