ios - 尽管图像很大,但 UIImageView 在 UICollectionViewCell 中显得很小

标签 ios iphone swift

使用自动布局,我创建了 UICollectionView 并在其中添加了一个 UIImageView 以显示各种类别图像。但是当我运行该应用程序时,尽管该单元格在屏幕上占据了适当的区域,但其中包含的 UIImageView 显得非常小。任何建议如何解决这个问题?我正在使用 Swift。

使用自动布局的 Pin 选项,我已将 UIImageView 固定到 UICollectionViewCell 的所有边缘。

在 Xcode Storyboard中它看起来像这样: Cell Size is 150 x 150

运行应用程序后,它看起来像这样: App view in simulator

我希望 UIImageView 覆盖单元格的所有绿色空间以显示图像。我正在使用以下代码来填充 UICollectionView

@IBOutlet weak var categoryCollectionView: UICollectionView!

let categoryImages = [UIImage(named: "cake"), UIImage(named: "flowers"), UIImage(named: "chocolate"), UIImage(named: "greetings"), UIImage(named: "combobox"), UIImage(named: "handicraft"), UIImage(named: "mug"), UIImage(named: "soft_toy")]

let categoryNames = ["Cakes", "Flowers", "Chocolates", "Greetings", "Combos", "Handicraft", "Mugs", "Soft Toys"]


func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.categoryNames.count;
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = categoryCollectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! HomeCategoriesCollectionViewCell


    cell.categoryImageView?.image = self.categoryImages[indexPath.row]

    cell.categoryNameLabel?.text = self.categoryNames[indexPath.row]

    return cell
}

最佳答案

看起来 contentView 没有填充您的代码返回的单元格宽度/高度。在 cellForItemAtIndexPath 中创建单元格后,您可以尝试设置 contentView 框架以匹配单元格的边界:

cell.contentView.frame = cell.bounds
cell.contentView.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | 
                         UIViewAutoresizing.FlexibleWidth | 
                         UIViewAutoresizing.FlexibleRightMargin |
                         UIViewAutoresizing.FlexibleTopMargin |
                         UIViewAutoresizing.FlexibleHeight | 
                         UIViewAutoresizing.FlexibleBottomMargin

或 swift 2

cell.contentView.frame = cell.bounds
cell.contentView.autoresizingMask = [.FlexibleLeftMargin,
                          .FlexibleWidth,
                          .FlexibleRightMargin,
                          .FlexibleTopMargin,
                          .FlexibleHeight,
                          .FlexibleBottomMargin]

关于ios - 尽管图像很大,但 UIImageView 在 UICollectionViewCell 中显得很小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33124223/

相关文章:

swift - 打开模块 'Swift' : Not a directory 的导入文件

ios - 根据内容自动增加 View 的高度

ios - 如何在 SwiftUI 中获取 iPhone 的屏幕宽度?

ios - BGTaskScheduler 提交调用失败,BGTaskSchedulerErrorDomain 代码为 : 1

ios - Cocos2d-iOS 中的设备方向

ios - UILabel 显示 1k 表示 int 值 1000 和 2k 表示 2000 等等

ios - 如何在进入后台后杀死 NSTimer 并在应用程序恢复事件后创建一个新计时器?

ios - 以编程方式滚动 UIScrollView,使 UILabel 位于导航栏下方

ios - 位置授权不提示

ios - Xcode Swift 暂停和恢复动画