我有收集視圖,您可以選擇4個按鈕,它就像A,B,C,D的測驗。我需要存儲他們點擊之前,他們去下一個問題(他們將滑動以轉到下一個問題,因爲它是一個集合視圖)控制器看起來像這樣:存儲按鈕按快速
第一:本質上用於顯示上述圖像的代碼,我已經創建了使用該解析的數據庫:
struct Question {
let fact: String
let question: String
let answers: [String: String]
let correctAnswer: String
let revenue: String
init?(with dictionary: [String: Any]) {
guard let fact = dictionary["fact"] as? String,
let question = dictionary["question"] as? String,
let answerA = dictionary["answer_a"] as? String,
let answerB = dictionary["answer_b"] as? String,
let answerC = dictionary["answer_c"] as? String,
let answerD = dictionary["answer_d"] as? String,
let revenue = dictionary["revenue"] as? String,
let correctAnswer = dictionary["correctAnswer"] as? String else { return nil }
self.fact = fact
self.question = question
self.revenue = revenue
var answersDict = [String: String]()
answersDict["answer_a"] = answerA
answersDict["answer_b"] = answerB
answersDict["answer_c"] = answerC
answersDict["answer_d"] = answerD
self.answers = answersDict
self.correctAnswer = correctAnswer
}
第二:然後我顯示使用此代碼:
extension QuestionCell {
func configure(with model: Question) {
factLabel.text = model.fact
questionLabel.text = model.question
revenueLabel.text = model.revenue
let views = answersStack.arrangedSubviews
for view in views {
view.removeFromSuperview()
}
for (id, answer) in model.answers {
print(index)
print(id)
let answerLabel = UILabel()
answerLabel.text = answer
answersStack.addArrangedSubview(answerLabel)
let answerButton = UIButton()
let imageNormal = UIImage(named: "circle_empty")
answerButton.setImage(imageNormal, for: .normal)
let imageSelected = UIImage(named: "circle_filled")
answerButton.setImage(imageSelected, for: .selected)
answerButton.setTitleColor(.black, for: .normal)
answerButton.addTarget(self, action: #selector(answerPressed(_:)), for: .touchUpInside)
answersStack.addArrangedSubview(answerButton)
}
}
}
有沒有辦法存儲我點擊的按鈕?謝謝
我不知道你是什麼意思本:沒有與此一個明顯的問題,那就是,這將不與集合視圖的工作,因爲你只有4個按鈕整個測驗不適用於每個視圖控制器。你能再描述一下嗎? – toddg
由於我有一個集合,它意味着你在許多控制器之間滑動,並且這4個按鈕將在那裏用於每個控制器。用於爲每個按鈕創建操作的方法將不起作用,因爲我只有4個按鈕。這有意義嗎? – josh
但是,當您滑動到一組新問題時,我假設您保存答案並加載新問題/答案集。當你創建你的'answerButton'時,你可以添加'answerButton.tag = index + 100'嗎?然後在'answerPressed'中拉出可以告訴你選擇的答案的標籤。 – toddg