如何在 Swift 4 中通过 SwiftyJson 和 Alamofire 创建多个按钮?

Posted

技术标签:

【中文标题】如何在 Swift 4 中通过 SwiftyJson 和 Alamofire 创建多个按钮?【英文标题】:How can I create multiple button by SwiftyJson and Almofire in swift 4? 【发布时间】: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 的完成闭包中调用该函数。 是的,你是对的。我在您回答之前就做到了,并得到了解决方案。无论如何谢谢。 【参考方案1】:

我找到了解决方案。添加按钮应在 Json 加载完成后运行:

var cats = [[String:AnyObject]]()
_ = 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) 

            print(responseData.request!)  // original URL request
            print(responseData.response!) // URL response

            let getJson = JSON(responseData.result.value!)

            if (getJson["status"].stringValue == "200")

                if let resData = getJson["data"].arrayObject 
                    self.cats = resData as! [[String:AnyObject]]
                
                if self.cats.count > 0 
                    self.addButton()
                

             else if (getJson["status"].stringValue == "404") 
                _ = SweetAlert().showAlert("Ok", subTitle: "Api Error!", style: AlertStyle.warning)
             else 
                _ = SweetAlert().showAlert("Error", subTitle: getJson["message"].stringValue, style: AlertStyle.warning)
            

        

        _ = EZLoadingActivity.hide()
    


func addButton()


    var buttonY: CGFloat = 20  // our Starting Offset, could be 0
    for villain in self.cats 

        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)
        self.view.addSubview(villainButton)  // myView in this case is the view you want these buttons added
    

请注意这部分代码:

if self.cats.count > 0 
                self.addButton()
            

感谢您的出席。

【讨论】:

您添加了真正的 API 密钥,我建议您在使用的任何服务上将其无效。

以上是关于如何在 Swift 4 中通过 SwiftyJson 和 Alamofire 创建多个按钮?的主要内容,如果未能解决你的问题,请参考以下文章

如何在IOS APP中通过swift/javascript登录网站

如何使用 Multipeer Connectivity (Swift 3) 在会话中通过 didReceiveData() 调用 table.reloadData

如何在 Swift 中通过 Segue 将数据传递到下一个视图?

如何在 Swift 中从 NSData 显示 PDF - 如何将 PDF 保存到文档文件夹 Swift - 如何在 Swift 中通过 WebView 从保存的 NSData 显示 PDF

如何在swift ios中通过键值读取子数据或过滤firebase数据

如何在 Swift 中通过 MR 的 id 从 coredata 中选择一条记录