尽管图像很大,UIImageView在UICollectionViewCell中显得非常小

时间:2015-10-14 11:33:44

标签: ios iphone swift

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

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

在Xcode故事板中,它看起来像这样: 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
}

1 个答案:

答案 0 :(得分:6)

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

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]