以编程方式创建按钮

Creating Button programmatically

我有一个方法 正在遍历 JSON 文件

var items = [JSON]()
func getDataFromJSON(){
    //Calling getCollectionViewData from the RestParser class
    RestParser.sharedInstance.getConfig{json in
        //iterating to the JSON file to get alle data
        let results = json[0]["menu"]
        for (index: String,cofigData:JSON)in results{
          self.items.append(cofigData)
          self.createButton()
        }
        println(self.items.count)
        println(json)
    }

} 

我和我希望 "json array" 中有尽可能多的结果来创建按钮,但有些如何只创建一个按钮,我不知道为什么?

这就是我创建按钮的方式

func createButton(){

   let button   = UIButton.buttonWithType(UIButtonType.System) as! UIButton
    button.frame = CGRect(x: 100,y: 100,width: 100,height: 50)
    button.backgroundColor = UIColor.blackColor()
    //button.setTitle("", forState: UIControlState.Normal)
    button.setTitle("Test", forState: UIControlState.Normal)
    button.addTarget(self, action: "buttonAction", forControlEvents: UIControlEvents.TouchUpInside)

    self.view.addSubview(button)
}

它确实创建了很多按钮,但由于所有按钮都有一个框架 CGRect(x: 100,y: 100,width: 100,height: 50) 它们彼此重叠。这就是为什么你只看到一个。您需要为每个按钮分配自己的框架

更新:

func createButton(index : Int){

 let button   = UIButton.buttonWithType(UIButtonType.System) as! UIButton
button.frame = CGRect(x: 100,y: 100 * index,width: 100,height: 50)
button.backgroundColor = UIColor.blackColor()
//button.setTitle("", forState: UIControlState.Normal)
button.setTitle("Test", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonAction", forControlEvents: UIControlEvents.TouchUpInside)

self.view.addSubview(button)

}

那么你只需要传入createButton方法当前迭代索引