UICollectionViewLayout在Swift 5和Xcode 11中无法与UIImage一起使用

问题描述 投票:0回答:2

请检查此随附的代码和屏幕简短。当我设置容器视图的颜色时,它工作正常,但是当我在单元格中添加UIImage时,它就无法工作。我更改了imageview内容模式,但无法正常工作。

class ViewController: UIViewController {

@IBOutlet weak var segColumn: UISegmentedControl!
@IBOutlet weak var collectionView: UICollectionView!

fileprivate var items: [UIImage] = [ // My images ]

override func viewDidLoad() {
    super.viewDidLoad()
    self.setup()
}
}

extension ViewController: UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items.count
    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
    cell.imgCell.image = items[indexPath.row]
    cell.imgCell.contentMode = .scaleAspectFill
    cell.contentView.backgroundColor = .red
    return cell
}
}

extension ViewController: UICollectionViewDelegateFlowLayout{

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (collectionView.bounds.width/3 - 2), height: (collectionView.bounds.width/3))
    }


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 2
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 2
    }
}

Not working with UIImage

working when remove UIImage

swift uicollectionview uiimageview uiimage uicollectionviewlayout
2个回答
1
投票

可能是因为红色在图像上占主导地位

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
    cell.imgCell.image = items[indexPath.row]
    cell.imgCell.contentMode = .scaleAspectFill
    cell.contentView.backgroundColor = .red
    return cell
}

尝试:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
    cell.contentView.backgroundColor = .red
    cell.imgCell.image = items[indexPath.row]
    cell.imgCell.contentMode = .scaleAspectFill

    return cell
}

0
投票

请尝试此解决方案。我认为Xcode 11会有一些变化。将CollectionView估计大小更改为“无”即可。

Please select your storyboard file

© www.soinside.com 2019 - 2024. All rights reserved.