我发现了一些关于UICollectionView和iwrong图像问题的帖子,但所有这些都有一个共同点 - 人们试图在cellForItemAt方法中下载图像。 我已经在我的应用程序包中有适当的图像,只需使用UIImage(命名:)方法将其设置为UICollectionViewCell。但是我仍然得到错误的图像。有谁可以帮助我?
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return liveChannels.count()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ChannelButtonViewCell", for: indexPath) as! ChannelButtonViewCell
let current = liveChannels.channels[indexPath.row]
let currentProgram = current.currentProgram()
let channelKey = current.channel?.channelKey
let programDetail = currentProgram?.name
if let currentProgress = currentProgram?.progress() {
cell.progressView.setProgress(currentProgress, animated: true)
}
print("\(channelKey) - \(current.channel!.logoName)")
cell.imageName = current.channel!.logoName
cell.channelTitleLabel.text = channelKey
cell.channelDetailLabel.text = programDetail
cell.channelButton.addTarget(self, action: #selector(ChannelsViewController.pressed(_:)), for: .primaryActionTriggered)
return cell
}
我将channelKey和logoName打印到控制台,以确保将正确的图像存储在liveChannels.channels结构中。 (确实如此)。
这是我的手机:
class ChannelButtonViewCell: UICollectionViewCell {
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var channelButton: ChannelButton!
@IBOutlet weak var channelDetailLabel: UILabel!
@IBOutlet weak var channelTitleLabel: UILabel!
@IBOutlet weak var channelImageView: UIImageView!
var imageName: String?
override func prepareForReuse() {
channelImageView.image = nil
super.prepareForReuse()
}
override func draw(_ rect: CGRect) {
if (self.isSelected) {
if let imageName = imageName {
channelImageView.image = UIImage(named: imageName)
}
} else {
if let imageName = imageName {
channelImageView.image = UIImage(named: imageName.appending("_grey"))
}
}
}
}
答案 0 :(得分:1)
1)你应该在非常罕见的情况下覆盖func draw(_ rect: CGRect)
而你的情况肯定不是那个。
2)为了确保在分配单元格var imageName: String?
时加载和更改图像正好,您可以使用Swift的didSet
3)为确保在选择状态更改时更新图像,您也可以使用didSet
。
你最终可能会删除func draw
并添加didSet
个观察者:
class ChannelButtonViewCell: UICollectionViewCell {
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var channelButton: ChannelButton!
@IBOutlet weak var channelDetailLabel: UILabel!
@IBOutlet weak var channelTitleLabel: UILabel!
@IBOutlet weak var channelImageView: UIImageView!
var imageName: String? {
didSet {
updateImage()
}
}
override var isSelected: Bool {
didSet {
updateImage()
}
}
override func prepareForReuse() {
channelImageView.image = nil
super.prepareForReuse()
}
func updateImage() {
guard let imageName = self.imageName else { return }
if (self.isSelected) {
channelImageView.image = UIImage(named: imageName)
} else {
channelImageView.image = UIImage(named: imageName.appending("_grey"))
}
}
}
如果此解决方案无法解决您的问题,请尝试在func draw()
内设置断点并检查它何时被调用以及var imageName
中存储的值