我有一个方法,正在迭代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数组"创建按钮,但有些如何只创建一个按钮,我不知道为什么?
这就是我按钮的方式
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)
}
答案 0 :(得分:4)
它确实创建了很多按钮,但由于它们都有一个框架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
方法当前迭代索引