【发布时间】:2018-09-29 03:08:40
【问题描述】:
这是我的努力:
var cats = [[String:AnyObject]]()
func getAllCats(){
_ = EZLoadingActivity.show("Loading...", disableUI: true)
let param: [String: AnyObject] = ["apiKey": "???" as AnyObject]
_ = Alamofire.request(APIRouters.GetAllCats(param)).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let getJson = JSON(responseData.result.value!)
if (getJson["status"].stringValue == "200"){
if let resData = getJson["data"].arrayObject {
self.cats = resData as! [[String:AnyObject]]
}
} else if (getJson["status"].stringValue == "404") {
} else {
}
}
_ = EZLoadingActivity.hide()
}
}
var buttonY: CGFloat = 20 // our Starting Offset, could be 0
for villain in cats {
print("ok",villain["pt_name_Fa"])
let villainButton = UIButton(frame: CGRect(x: 50, y: buttonY, width: 250, height: 30))
buttonY = buttonY + 50 // we are going to space these UIButtons 50px apart
villainButton.layer.cornerRadius = 10 // get some fancy pantsy rounding
villainButton.backgroundColor = UIColor.darkGray
villainButton.setTitle("Button for Villain: \(villain["pt_name_Fa"] ?? "" as AnyObject))", for: UIControlState.normal) // We are going to use the item name as the Button Title here.
villainButton.titleLabel?.text = "\(villain)"
villainButton.addTarget(self,action:#selector(villainButtonPressed),
for:.touchUpInside)
// villainButton.addTarget(self, action: Selector(("villainButtonPressed:")), for: UIControlEvents.touchUpInside)
self.view.addSubview(villainButton) // myView in this case is the view you want these buttons added
}
它不起作用,但如果我使用下面这样的数组,它会起作用! var arrayOfVillains = [“圣诞老人”、“虫子”、“超人”、“蝙蝠侠”]
提前感谢您的帮助
【问题讨论】:
-
获取是异步完成的,因此当您尝试创建按钮时,
cats尚未填充。您需要将按钮创建代码移动到一个函数中,并从传递给 Alamofire 的完成闭包中调用该函数。 -
是的,你是对的。我在您回答之前就做到了,并得到了解决方案。无论如何谢谢。
标签: ios swift swift4 alamofire swifty-json