collectionviewのセルから遷移した画面でボタンを押すとセルの画像が変わる、というものを作りたいと思っています。
現在画像を保存している配列の中身を変えるところまでは出来るようになったのですが配列の中身が変わっただけでセルの画像は変わりません。(再起動後にcollectionviewを開くと変わっています)
セルの画像を表示するのがcollectionviewを開いた最初一回のみなので再起動後にしか画像が変わらないのだと思います。
セルの更新というのがあるようなのですがよくわからないので教えてもらえると助かります。
※知識不足なためコードがとてもわかりづらくなってます
UserDefaultsにstringや直接配列を入れたかったのですがうまくいかず、数字のみを受け渡してそこから数字によって配列の中身を変えるようにしています。
遷移した先でボタンを押すとimageの数字が0から1に変わり、collectionviewに戻った時1になっていたら配列の中身が変わるというものにしています。
if image1 == 1{
imageNames2[0] = "xyz.jpg"
}
の中に更新するものを入れることができればうまくいくのではないかと思っています。
import UIKit class ViewController: UIViewController ,UICollectionViewDataSource, UICollectionViewDelegate { let photos:Array<String> = ["1","2"] var imageNames2:[String] = ["abc.jpg","abc.jpg"] var image1 = 0 var image2 = 0 override func viewDidLoad() { super.viewDidLoad() } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let testCell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) let imageView = testCell.contentView.viewWithTag(1) as! UIImageView let cellImage = UIImage(named: imageNames2[(indexPath as NSIndexPath).row]) imageView.image = cellImage let label = testCell.contentView.viewWithTag(2) as! UILabel label.text = photos[(indexPath as NSIndexPath).row] return testCell } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photos.count; } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if (indexPath as NSIndexPath).row == 0 { performSegue(withIdentifier: "vc0", sender: nil) } else if indexPath.row == 1 { performSegue(withIdentifier: "vc1", sender: nil) } } override func viewWillAppear(_ animated: Bool) { super.viewDidLoad() let image1 = UserDefaults.standard.integer(forKey: "image1") if image1 == 1{ imageNames2[0] = "xyz.jpg" } let image2 = UserDefaults.standard.integer(forKey: "image2") if image2 == 1{ imageNames2[1] = "xyz.jpg" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/11/29 14:35