Swift 按钮数组

Swift Button Array

Swift + SQLite 项目中,我试图在我的 UI 中填充一个包含 4 个按钮的数组SQL查询。到目前为止我能做的最好的就是下面的代码所示,但我相信它可以以更简洁的方式完成。我试图在同一个循环中同时执行 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
    }
  }   
 }

您收到引用错误,因为您将数组声明为 IBoutlet 。如果您的 answerButton 具有 UIButton 对象,则不应该是 @IBOutlet var answerButton: Array = []。 answerButton 声明如下 var answerButton: Array = [].

如果您想测试下面的代码,请根据您的代码修改下面的代码,而不仅仅是将其复制并粘贴到 viewcontroller 的 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)
    }
}
var buttons: [UIButton?] {
    return [self.firstButton, self.secondButton, self.thirdButton]
}