Я сделал свое самое первое приложение для iOS.Но есть две досадные ошибки, от которых я не могу избавиться.Я надеюсь, что кто-нибудь может мне помочь!
Приложение должно обучаться читать музыкальные записи.Пользователь указывает свой инструмент и уровень (на предыдущем контроллере представления) и на основании этого он помещает случайные ноты в музыкальные записи на экране.Пользователь должен сопоставить эти заметки в текстовых полях, а приложение отслеживает оценку и повышает уровень после десяти правильных ответов.
Однако у меня почему-то возникают проблемы с функцией, которая генерирует случайные заметки.По какой-то причине функция вызывается дважды, при первом создании заметок, сохранении их в глобальной переменной и создании меток с заметками.Во второй раз он изменяет глобальную переменную, но не метки.На этот раз он возвращает следующее сообщение об ошибке: 2018-09-29 23:08:37.279170+0200 MyProject[57733:4748212] Warning: Attempt to present <MyProject.ThirdViewController: 0x7fc709125890> on <MyProject.SecondViewController: 0x7fc70900fcd0> whose view is not in the window hierarchy!
Из-за этого пользователь отвечает на вопрос на экране, но приложение считает, что это неправильный ответ, поскольку у него хранится второй ответ.
ВторойКогда пользователь отвечает на вопрос, функция вызывается только один раз, но показания из текстовых полей не обновляются до новых значений, но остаются такими же, как и в первом вопросе.
Вот код, который дает проблемы:
import UIKit
class ThirdViewController: UIViewController
{
// snip
func setupLabels() {
// snip
// here the random notes are created, this is function is called multiple times for some reason
let antwoord = Noten()
let antwoordReturn = antwoord.generateNoten(instrument: instrument, ijkpunt: ijkpunt, aantalNoten: aantalNoten-1)
let sleutel = antwoordReturn.0
let heleOpgave = antwoordReturn.1
print(heleOpgave)
print(PassOpgave.shared.category)
let heleOpgaveNummers = antwoordReturn.2
// snip
var a = 0
while a < aantalNoten {
// the labels are created, no problems there
let myTekstveld = UITextField(frame: CGRect(x: labelX, y: labelY + 150, width: labelWidth, height: labelHeight / 2))
myTekstveld.backgroundColor = UIColor.white
myTekstveld.textAlignment = .center
myTekstveld.placeholder = "?"
myTekstveld.keyboardType = UIKeyboardType.default
myTekstveld.borderStyle = UITextField.BorderStyle.line
myTekstveld.autocorrectionType = .no
myTekstveld.returnKeyType = UIReturnKeyType.done
myTekstveld.textColor = UIColor.init(displayP3Red: CGFloat(96.0/255.0), green: CGFloat(35.0/255.0), blue: CGFloat(123.0/255.0), alpha: 1)
myTekstveld.delegate = self as? UITextFieldDelegate
myTekstveld.tag = a + 1
view.addSubview(myTekstveld)
a += 1
labelX += labelWidth
}
// the button is created
}
override func viewDidLoad()
{
super.viewDidLoad()
// snip
setupLabels()
}
@objc func buttonAction(sender: UIButton!) {
// snip
// here the text from the text fields is read, but this only works the first time the buttonAction is called, the next times, it simply returns the first user input.
while a <= aantalNoten {
if let theLabel = view.viewWithTag(a) as? UITextField {
let tekstInput = theLabel.text!
userInput.append(tekstInput)
}
a += 1
}
// snip
setupLabels()
return
}
// snip