2015-06-02 132 views
1

Swift + SQLite項目我試圖用SQL查詢在我的UI中填充4個按鈕的數組。到目前爲止我能做的最好的代碼如下所示,但我相信它可以以更清晰的方式完成。我試圖在同一個循環中同時執行SQL查詢結果讀取和按鈕更改,但得到各種類型的類型不匹配和參考錯誤
任何建議將不勝感激。快速按鈕陣列

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 
    } 
    } 
} 
+0

你能解釋更多嗎??????? –

+0

如果您的SQL查詢需要很長時間會發生什麼?然後我期望你的結果是空的,而你的其他代碼執行 –

回答

2

由於您正在將數組聲明爲IBoutlet,因此您將收到引用錯誤。如果您的answerButton具有UIButton的對象應該不是@IBOutlet var answerButton:Array = []。 answerButton這樣聲明var answerButton:Array = []

請,如果你想測試下面的代碼不僅僅是複製根據您的代碼修改下面的代碼和過去的入FUNC viewDidLoad中()您的視圖 - 控制的,這會告訴你四個按鈕就可以查看

 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) 
    } 
} 
0
var buttons: [UIButton?] { 
    return [self.firstButton, self.secondButton, self.thirdButton] 
} 
+1

一些解釋這段代碼做什麼以及它如何解決這個問題會很好。 – JJJ