我正在创建一个pokedex应用程序,我希望它的工作方式基本上是在屏幕顶部有一个滚动条,允许您选择任何精灵宝可梦,一旦选择精灵宝可梦,在滚动条下面将显示精灵宝可梦条目(bulbasaur将默认存在,直到选择了精灵宝可梦,因为bulbasaur是第一个ID为1的精灵宝可梦)。为了实现这一点,我让我的视图控制器返回两种类型的单元格,第一种是"chooser单元格“,它是滚动条,第二种是"description单元格”,它是dex条目。我向视图控制器提供了一个名为dex entry的数据成员,并在cellForItemAt函数中返回了dex entry,但是单元的图像没有改变(从bulbasaur到我选择的任何pokemon )。每次选择pokemon时,我都会向控制台打印dex entry的pokemon的值是什么,所以我确信dex条目正在被直接更改,但我不知道为什么图像没有更改。下面是我的代码的相关部分。
视图控制器(仅部分):
import UIKit
class PokeDexController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var dexEntry = DescriptionCell()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "PokeDex 386"
collectionView?.backgroundColor = UIColor(red: 52/255.0, green: 55/255.0, blue: 64/255.0, alpha: 1.0)
//collectionView?.backgroundColor = UIColor.white
collectionView?.register(chooserCell.self, forCellWithReuseIdentifier: cellID)
collectionView?.register(DescriptionCell.self, forCellWithReuseIdentifier: descID)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if (indexPath.row == 0)
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! chooserCell
return cell
}
else{
let descCell = collectionView.dequeueReusableCell(withReuseIdentifier: descID, for: indexPath) as! DescriptionCell
dexEntry = descCell
return dexEntry
}
}descriptionCell类:
import UIKit
class DescriptionCell: UICollectionViewCell
{
private var pokemon : Pokemon?
{
didSet
{
if let id = pokemon?._id
{
imageView.image = UIImage(named: String(id))
print("Pokemon with the id of " + String(id))
}
}
}
override init(frame: CGRect)
{
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setPokemon(poke: Pokemon)
{
self.pokemon = poke
}
func getPokemon() -> Pokemon
{
return pokemon!
}
let imageView: UIImageView =
{
let iv = UIImageView()
iv.image = UIImage(named: "1")
iv.contentMode = .scaleAspectFill
return iv
}()
func setupViews()
{
backgroundColor = UIColor(red: 52/255.0, green: 55/255.0, blue: 64/255.0, alpha: 1.0)
addSubview(imageView)
imageView.frame = (CGRect(x: frame.width/6, y: frame.height/30, width: frame.width/4, height: frame.height/4))
}}
choosercell类(特别是didSelectItemAt):
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
let poke = pokemon[indexPath.row]
print("Selected " + poke._name)
let vc = PokeDexController()
vc.dexEntry.setPokemon(poke: poke)
let name = vc.dexEntry.getPokemon()._name
print(name ?? "nothing there")
}image of the app and the console output
感谢您的帮助,谢谢。
发布于 2017-01-24 10:08:21
我还没有解决我的问题,但是我意识到我在我的viewController中返回的单元格是独立于dexEntry的,所以一旦单元格被设置,它就被设置了,所以我现在将弄清楚当一个单元格被选中时如何重新加载,这样返回的单元格就有一个不同的口袋妖怪的图像。
https://stackoverflow.com/questions/41807735
复制相似问题