无法从URL将图像加载到Swift中的UICollectionViewCell中

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

我有一个像这样的简约UICollectionViewCell:

class CampaignTileViewCellController: UICollectionViewCell {

    @IBOutlet weak var CampaignBackgroundImage: UIImageView!
}

并跟随UIViewController:

class CoopOverviewViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var CampaignBrandSliderBackground: UIView!
    @IBOutlet weak var CampaignBrandSlider: UISegmentedControl!
    @IBOutlet weak var CampaignCollectionView: UICollectionView!

    // TODO: replace foo with TableView listing brands
    @IBOutlet weak var foo: UIView!

    let apiService = APIService()
    var campaigns: [Campaign] = []


    override func viewDidLoad() {
        super.viewDidLoad()
        CampaignBrandSliderBackground.layer.cornerRadius = 10
        foo.isHidden = true

        // load Campaigns
        self.apiService.getCampaignList(completion: {result in
            switch result {
            case .success(let campaigns):
                DispatchQueue.main.async {
                    print("NUMBER OF CAMPAIGNS: ", campaigns.count)
                    print("CAMPAIGN IMG: ", campaigns[0].img)
                    self.campaigns = campaigns
                }
            case .failure(let error):
                print("An error occured \(error.localizedDescription)")
            }
        })

        // Conform to UICollectionViewDelegate Protocol:
        CampaignCollectionView.dataSource = self
        CampaignCollectionView.delegate = self


        // Adjust Layout of CollectionViewCell: set cell height so that the collection fits 3 cells
        var cellLayout = self.CampaignCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        cellLayout.itemSize = CGSize(width: self.CampaignCollectionView.frame.size.width, height: self.CampaignCollectionView.frame.size.height/3)
    }

    // Conform to UICollectionViewDataSource Protocol:
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return campaigns.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        print("was here too")
        let campaignCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CampaignTileViewCell", for: indexPath) as! CampaignTileViewCellController
        let imgURL = URL(string: campaigns[indexPath.item].img!)
        let img = try? UIImage(withContentsOfUrl: imgURL!)
        campaignCell.CampaignBackgroundImage.image = img

        return campaignCell
    }

    @IBAction func CampaignBrandSliderIndexChanged(_ sender: Any) {
        switch CampaignBrandSlider.selectedSegmentIndex {
        case 0:
            CampaignCollectionView.isHidden = false
            foo.isHidden = true
        case 1:
            CampaignCollectionView.isHidden = true
            foo.isHidden = false
        default:
            break
        }
    }

}

extension UIImage {

    convenience init?(withContentsOfUrl url: URL) throws {
        let imageData = try Data(contentsOf: url)

        self.init(data: imageData)
    }

}

我收到了正确的api响应,并带有有效的https图像链接,该链接已通过print语句进行了验证。不过,它只是不会在collectionview中显示图像。但是,如果我要像下面所示那样硬连接图像,则可以使用。

class CoopOverviewViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var CampaignBrandSliderBackground: UIView!
    @IBOutlet weak var CampaignBrandSlider: UISegmentedControl!
    @IBOutlet weak var CampaignCollectionView: UICollectionView!

    // TODO: replace foo with TableView listing brands
    @IBOutlet weak var foo: UIView!

    // TODO: load real data and replace with campaign model
    let campaignImages: [UIImage] = [UIImage(named: "icon-black")!,UIImage(named: "icon-white")!,UIImage(named: "icon-black")!,UIImage(named: "icon-white")!]
    let apiService = APIService()
    var campaigns: [Campaign]

    override func viewDidLoad() {
        super.viewDidLoad()
        CampaignBrandSliderBackground.layer.cornerRadius = 10
        foo.isHidden = true

        // load Campaigns
        self.apiService.getCampaignList(completion: {result in
            switch result {
            case .success(let campaigns):
                DispatchQueue.main.async {
                    print("NUMBER OF CAMPAIGNS: ", campaigns.count)
                    print("CAMPAIGN DATA: ", campaigns[0].name)
                    self.campaigns = campaigns
                }
            case .failure(let error):
                print("An error occured \(error.localizedDescription)")
            }
        })


        // Conform to UICollectionViewDelegate Protocol:
        CampaignCollectionView.dataSource = self
        CampaignCollectionView.delegate = self


        // Adjust Layout of CollectionViewCell: set cell height so that the collection fits 3 cells
        var cellLayout = self.CampaignCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        cellLayout.itemSize = CGSize(width: self.CampaignCollectionView.frame.size.width, height: self.CampaignCollectionView.frame.size.height/3) // TODO: custom height seems to get ignored
    }

    // Conform to UICollectionViewDataSource Protocol:
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return campaignImages.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let campaignCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CampaignTileViewCell", for: indexPath) as! CampaignTileViewCellController
        campaignCell.CampaignBackgroundImage.image = campaignImages[indexPath.item]

        return campaignCell
    }

    @IBAction func CampaignBrandSliderIndexChanged(_ sender: Any) {
        switch CampaignBrandSlider.selectedSegmentIndex {
        case 0:
            CampaignCollectionView.isHidden = false
            foo.isHidden = true
        case 1:
            CampaignCollectionView.isHidden = true
            foo.isHidden = false
        default:
            break
        }
    }
}

任何人都可以提供帮助吗?

swift uicollectionview uiimage uicollectionviewcell
1个回答
1
投票

您需要重新加载

DispatchQueue.main.async {
    print("NUMBER OF CAMPAIGNS: ", campaigns.count)
    print("CAMPAIGN DATA: ", campaigns[0].name)
    self.campaigns = campaigns
    self.campaignCollectionView.reloadData()
}

SDWebImage加载图像

campaignCell.campaignBackgroundImage.sd_setImage(with: URL(string:campaignImages[indexPath.item].url), placeholderImage: UIImage(named: "placeholder.png")) 
© www.soinside.com 2019 - 2024. All rights reserved.