ios - 如何使图像适合CollectionView?

标签 ios swift uicollectionview uicollectionviewcell

目前我有下图:
enter image description here

我想在容器中插入图片。
但是当我运行这段代码

//MARK: - UICollectionViewDataSource protocol

// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.items.count
}
//make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    //get  a reference to our storyboard cell
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! AppIconViewCell

    // Use the outlet in our custom class to get a reference to the UILabel in the cell
    cell.myLabel.text = self.items[indexPath.item]
    cell.ImageView.image = UIImage.init(named: "page-01")

    //cell.backgroundColor = UIColor.cyan
    cell.layer.borderColor = UIColor.black.cgColor
    cell.layer.borderWidth = 1
    cell.layer.cornerRadius = 8

    return cell
}

结果是这样的:
enter image description here

我的理解是图像大于框架,导致框架扩大。

如何在内部设置图像,使其适合第一张图像中的框?

最佳答案

欢迎使用Stackoverflow。

为此,您需要添加显式的高度宽度约束。我假设您具有返回sizeForItemAt方法的适当大小。

最后,不要忘记将cellImageViewclipsToBounds设置为true

关于ios - 如何使图像适合CollectionView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60922411/

相关文章:

jquery - 无法选择带有类的 div

SwiftUI:什么替代了委托(delegate)协议(protocol)?

ios - 通知消息/警报消息和 UICollectionView :

ios - 动画 UICollectionViewFlowLayout 子类 UICollectionViewLayoutAttributes 框架变化

ios - UISlider thumbTintColor 在 iOS 7 上没有改变(在 iOS 6 上很好)

ios - TableView 选定的单元格 - 当滚动到视线之外且选中新单元格时,复选标记消失

ios - 无法使用 swift 在 iPhone 6 中注册远程通知

swift - 禁止直接赋值的可变属性 - Swift

ios - 使用 REST 使捆绑 Realm 保持最新

swift - 为什么我的 Collection View 单元格返回错误 "The dequeued cell is not an instance of TileCollectionViewCell"