gpt4 book ai didi

ios - UICollectionView 自定义单元格以在 Swift 中填充宽度

转载 作者:IT王子 更新时间:2023-10-29 05:03:05 25 4
gpt4 key购买 nike

我一直在想办法让单元格填满宽度,正如您在图片中看到的那样,单元格之间的宽度太大了。我正在使用只有一个 imageView 的自定义单元格。

enter image description here

我试图从 Storyboard 中对其进行自定义,但我想没有为此的选项,或者应该以编程方式完成。 enter image description here

我的 UICollectionViewController :

 @IBOutlet var collectionView2: UICollectionView!

let recipeImages = ["angry_birds_cake", "creme_brelee", "egg_benedict", "full_breakfast", "green_tea", "ham_and_cheese_panini", "ham_and_egg_sandwich", "hamburger", "instant_noodle_with_egg.jpg", "japanese_noodle_with_pork", "mushroom_risotto", "noodle_with_bbq_pork", "starbucks_coffee", "thai_shrimp_cake", "vegetable_curry", "white_chocolate_donut"]

override func viewDidLoad() {
super.viewDidLoad()

// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false

// Do any additional setup after loading the view.

}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//#warning Incomplete method implementation -- Return the number of sections
return 1
}


override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//#warning Incomplete method implementation -- Return the number of items in the section
return recipeImages.count
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! RecipeCollectionViewCell

// Configure the cell
cell.recipeImageView.image = UIImage(named: recipeImages[indexPath.row])

return cell
}

最佳答案

您需要以编程方式执行此操作。

在您的 View Controller 中实现 UICollectionViewDelegateFlowLayout 并在 collectionView:layout:sizeForItemAtIndexPath: 中提供大小

func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let kWhateverHeightYouWant = 100
return CGSizeMake(collectionView.bounds.size.width, CGFloat(kWhateverHeightYouWant))
}

您还需要在 View Controller 的 viewWillLayoutSubviews() 中调用 collectionView.collectionViewLayout.invalidateLayout(),这样当主视图的尺寸发生变化时(旋转时,对于例如), Collection View 被重新布局。

swift 4 更新

func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let kWhateverHeightYouWant = 100
return CGSize(width: collectionView.bounds.size.width, height: CGFloat(kWhateverHeightYouWant))
}

关于ios - UICollectionView 自定义单元格以在 Swift 中填充宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29986379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com