在我的应用程序的最后一个 View Controller 中,我编写了一段代码,该代码创建了许多标签,这些标签填充了一组随机字符
标签下方出现文本字段,用户应在其中匹配标签中的字符。当他按下按钮时,他的答案就会被检查。如果答案正确,分数就会更新。
之后,分数标签应该更新,并且应该生成并显示带有字符的标签的新文本,但这就是我陷入困境的地方......我的本能是在 viewDidLoad 中的代码中添加一个循环,但是由于检查答案的代码位于viewDidLoad之外的buttonAction函数中,我不知道该怎么做...
这是我的应用程序中的一些代码,可能会澄清一些事情。我删除了很多简单的代码,并为本示例添加了注释行。
override func viewDidLoad()
{
super.viewDidLoad()
// variables are declared, the number of labels is calculated based on the frame size
// the text for the labels is calculated based on a function in a separate class I wrote
var a = 0
while a < numberOfLabels {
// the UILabels are made and filled
// the corresponding UITextFields are made
a += 1
labelX += labelWidth
}
// then here the button is coded, the last lines are:
myButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
view.addSubview(myButton)
}
@objc func buttonAction(sender: UIButton!) {
var a = 0
var rightAnswer = false
var userInput: [String] = Array()
while a < numberOfLabels.shared.category! {
if let theLabel = self.view.viewWithTag(a) as? UITextField {
let tekstInput = theLabel.text
userInput.insert(tekstInput!, at:a-1)
}
a = a + 1
}
let controle = Controle()
rightAnswer = controle.checkAnswer(userAnswer: userInput)
if rightAnswer {
if var score = PassScore.shared.category {
score += 1
PassScore.shared.category = score
}
else {
var score = 1
PassScore.shared.category = score
}
}
return
}
最佳答案
将初始化代码放在函数中
func setupLabels() {
var a = 0
while a < numberOfLabels {
// the UILabels are made and filled
// the corresponding UITextFields are made
a += 1
labelX += labelWidth
}
}
并在需要时调用它:
override func viewDidLoad()
{
super.viewDidLoad()
setupLabels()
}
@objc func buttonAction(sender: UIButton!) {
//...
setupLabels()
}
关于ios - 循环编程标签和按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52533251/