我有一个Collection View Controller
,这是我创建的徽标测验游戏的一个级别。如果用户猜到徽标,我会将其存储在UserDefaults
中并在Collection View
中检索,这会将复选标记图像放到单元格上。
一切正常,但当用户从测验视图返回Collection View Controller
时,检查标记未显示。但是,如果我返回级别菜单然后打开Collection View Controller
,则复选标记会正确显示。我尝试使用dispatch
方法解决此问题,但它没有帮助!我也尝试了CollectionView.reloadData
方法,但仍然没有任何反应!
import UIKit
class CollectionViewController: UICollectionViewController {
var array = ["Youtube.jpeg","Facebook.svg.png","Google.png","Burger King.png"]
var tappedImage = String()
var associatedString = ""
var expectedAnswer = ""
let defaults = UserDefaults.standard
var indexx = 0
var checked: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return array.count
}
//performSegueWithIdentifier("ShowColor", sender: sender)
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
let ImageView = cell.viewWithTag(1) as! UIImageView
ImageView.image = UIImage(named: array[indexPath.row])
let button = cell.viewWithTag(2) as! UIButton
button.tag = indexPath.row
button.addTarget(self, action: #selector(sendInformation), for: .touchUpInside)
let checkImage = cell.viewWithTag(3) as! UIImageView
var name = array[button.tag]
if let dotRange = name.range(of: ".") {
name.removeSubrange(dotRange.lowerBound..<name.endIndex)
expectedAnswer = name
}
if defaults.value(forKey: "\(expectedAnswer)") != nil{
let isChecked = defaults.value(forKey: "\(expectedAnswer)") as! Bool
if isChecked == true{
checkImage.image = UIImage(named: "checkmark1.png")
}
}
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "quizSegue" {
if let quizViewController = segue.destination as? QuizVC {
quizViewController.image = self.tappedImage
quizViewController.expectedAnswer = self.expectedAnswer
}
}
}
func sendInformation(_ sender: UIButton){
tappedImage = array[sender.tag]
var name = array[sender.tag]
if let dotRange = name.range(of: ".") {
name.removeSubrange(dotRange.lowerBound..<name.endIndex)
expectedAnswer = name
print(expectedAnswer)
}
self.performSegue(withIdentifier: "quizSegue", sender: nil)
}
@IBAction func unwindToCollectionView(segue: UIStoryboardSegue){
}
注意:您的答案可以在swift 2中,我可以轻松翻译它!我使用了swift 3。 非常感谢任何帮助!
答案 0 :(得分:0)
经过大量谷歌搜索,我终于解决了这个问题。在Collection View Controller
:
override func viewWillAppear(_ animated: Bool) {
let parent = self.view.superview
self.view.removeFromSuperview()
self.view = nil
// unloads the entire view
parent?.addSubview(self.view)
// reloads the view
}
collectionView.reloadData
无法正常工作,因为我有一个重新加载的按钮导致:
EXC_BAD指令
我刚强迫视图重新加载。我不会删除此问题,因为其他人可能会觉得它很有用......源代码来自reload/refresh subViews - setNeedsDisplay doesnt work。