我有集合视图,您可以在其中选择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)
}
}
}
有没有办法存储我点击的按钮?感谢
答案 0 :(得分:0)
在这种情况下,有一种确定的方法。
您应该考虑采用与此方法相近的方法来获得强大的解决方案。
答案 1 :(得分:0)
我过去处理此问题的方法是使用UIButton
上的标记,并跟踪当前选择的标记。使用这种方法,我可以为每个按钮使用相同的IBAction
,我需要做的就是从函数体中的sender
中提取标记。虽然使用子类化的方法可能不那么灵活和健壮,但实现起来要快一些。
首先在创建按钮时设置标签(我使用100-104以避免与其他按钮发生冲突)。由于您要在CollectionView中创建按钮,因此您需要在configure()
函数中设置标记:
func configure(with model: Question) {
...
for (id, answer) in model.answers {
...
answerButton.setImage(imageSelected, for: .selected)
answerButton.tag = index
answerButton.setTitleColor(.black, for: .normal)
answerButton.addTarget(self, action: #selector(answerPressed(_:)), for: .touchUpInside)
}
}
创建一个实例变量:
var selectedAnswerIndex = -1
然后将此IBAction分配给每个按钮:
func answerPressed(_ sender: UIButton){
selectedAnswerIndex = sender.tag
hilightNewOne(sender: sender)
}