swift - 无法将图像从 url 加载到 Swift 中的 UICollectionViewCell
问题描述
我有一个简约的 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 图像链接有效,我已通过打印语句进行了验证。不过,它只是不会在 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
}
}
}
有谁能帮忙吗?
解决方案
你需要重新加载
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"))
推荐阅读
- javascript - P5 - 使用动画 GIF 固定随机位置
- javascript - Angular 1.6 数据在后续加载时未刷新
- python - 计算文件每一行中的逗号数
- scala - 使用 JSONCollection 而不是 BSONCollection 的事务
- rest - 关于微服务模糊边界
- python - DuplicateWidgetID:有多个相同的 st.selectbox 小部件
- python - python中可能存在的错误。创建装饰器自动生成属性
- sql - MS Access:查询中的编号
- discord - 检查玩家是否被禁止、踢出或刚刚离开服务器
- python - 在函数“inRange”中(-215:断言失败)!_src.empty()