gpt4 book ai didi

swift - 在 Swift 中存储按下的按钮

转载 作者:行者123 更新时间:2023-11-30 12:14:38 25 4
gpt4 key购买 nike

我有一个 Collection View ,您可以在其中选择 4 个按钮,这就像一个包含 A、B、C、D 的测验。我需要存储他们在转到下一个问题之前单击的按钮(他们会滑动以转到下一个问题,因为它是 Collection View ) Controller 如下所示: enter image description here

首先:本质上是用于显示上面图像的代码,我创建了一个使用以下内容进行解析的数据库:

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)

}
}
}

有没有办法存储我点击的按钮?谢谢

最佳答案

好吧,有一个肯定的方法可以摆脱这种情况。

  1. 为collectionView创建一个自定义单元格。
  2. 在 customCell 类中添加按钮 socket 和操作
  3. 在 customCell 类中创建并使用委托(delegate)方法,并在 ViewController 中实现 customCell 时将委托(delegate)设置为 self 。
  4. 按钮操作完成后触发委托(delegate)方法(在自定义单元格内)。
  5. 在 cellForItemAt 方法中使用时,为您的 customCell 提供当前索引路径。
  6. 利用该索引路径来决定触发哪个按钮。

您应该考虑与此方法类似的方法,以获得可靠的解决方案。

关于swift - 在 Swift 中存储按下的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45578524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com