In a Swift + SQLite project I'm trying to populate an array of 4 buttons in my UI with a SQL query. The best I could do so far is as the code below shows, but I'm sure it can be done in a cleaner way. I tried to do both the SQL query result reading and button change in the same loop but got all sorts of type mismatch and reference errors.
Any suggestion will be much appreciated.
var answerText: Array<String?> = ["","","",""]
class ViewController: UIViewController {
@IBOutlet var answerButton: Array<UIButton> = []
func displayQuestion(questionNumber: Int){
let querySQL = "SELECT answer FROM answers WHERE answers.question = '\(questionNumber)'"
let results:FMResultSet? = myDatabase.executeQuery(querySQL,
withArgumentsInArray: nil)
var j=0
while results?.next() == true {
answerText[j] = results?.stringForColumn("answer")
j=j+1
}
j=0
for item in answerButton{
var button:UIButton = item as UIButton
button.setTitle(answerText[j], forState: UIControlState.Normal)
j=j+1
}
}
}
you are getting reference error because you are declaring an array as a IBoutlet . if your answerButton having objects of UIButton than that should not be @IBOutlet var answerButton: Array = []. answerButton declared like this var answerButton: Array = [].
please modify below code according to you code if you want to test the below code than just copy and past it into func viewDidLoad() of your viewcontroller and this will show you four buttons on you view
var answerText: Array<String?> = ["Button1","Button2","Button3","Button4"]
var answerButton: Array<UIButton> = []
for var i = 0; i<=answerText.count; i++ {
var button = UIButton.buttonWithType(.System) as! UIButton
button.titleLabel!.font = UIFont.systemFontOfSize(12)
button.titleLabel!.lineBreakMode = .ByTruncatingTail
var numberOfButton = 5
let j = i
var y:CGFloat = (CGFloat)(j*690/(numberOfButton+1)-21);
button.frame.size.height = 42
button.frame.size.width = 150
button.frame.origin.y = y
button.frame.origin.x = 250.0
answerButton .insert(button, atIndex: i)
}
for var i = 0; i<answerText.count; i++ {
var button:UIButton = answerButton [i]
button.setTitle(answerText[i], forState: UIControlState.Normal)
self.view .addSubview(button)
}
}