在我的应用程序的最后一个视图控制器中,我编写了一个代码,该代码创建了许多标签,这些标签中填充了一组随机字符
在标签文本字段下方显示用户应与标签字符匹配的位置。当他按下按钮时,将检查他的答案。如果答案正确,则分数会更新。
此后,乐谱标签应更新,应生成并显示带有字符的标签的新文本,但这就是我遇到的问题……我的本能是在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
}
答案 0 :(得分:0)
将初始化代码包含在函数中
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()
}