是否可以将两个Web服务数据实现到单个表视图中?

时间:2017-07-11 12:07:21

标签: ios uitableview swift3

在此我实现了使用两个表视图我需要它在单个表视图中实现它是否可能,如果可能的话,任何人都可以帮助我如何实现,在这我得到了所需的输出但我正在尝试在单个表视图上实现它,以便两个表视图之间的间距在横向期间更多,以便为了避免这种情况,我试图实现这一点,任何帮助都将非常值得赞赏

  let url = "http://www.json-generator.com/api/json/get/bMlqRPbjGW?indent=2"
    let urlString = "http://www.json-generator.com/api/json/get/bVWKKHtWbm?indent=2"
    var shippingArray :[[String: AnyObject]] = []
    var keys = [String]()
    let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    var arrayss =  [String:Any]()
    var checkIsRadioSelect = [Int]()
    var checkIsButtonEnable = [Int]()
    var checkIsPaymentRadioSelect = [Int]()
    let response : [Int] = []
    var chekIndex:IndexPath?
    var selected: Bool = false
    var dataArray = [[String:AnyObject]]()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableDetails.isHidden = true
        shippingTableView.isHidden = true
        titleLabel.isHidden = true
        newAddress.layer.cornerRadius = 5
        continueButton.layer.cornerRadius = 5
        myActivityIndicator.frame = CGRect(x: 130, y: 320, width: 30, height: 30)
        myActivityIndicator.hidesWhenStopped = true
        myActivityIndicator.startAnimating()
        view.addSubview(myActivityIndicator)
        myActivityIndicator.translatesAutoresizingMaskIntoConstraints = false
        let horizontalConstraint = NSLayoutConstraint(item: myActivityIndicator, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
        view.addConstraint(horizontalConstraint)
        let verticalConstraint = NSLayoutConstraint(item: myActivityIndicator, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
        view.addConstraint(verticalConstraint)
        self.shippingaddressURL()
        self.shippingmethodURL()
        tableDetails.delegate = self
        tableDetails.dataSource = self
        tableDetails.rowHeight = UITableViewAutomaticDimension
        tableDetails.estimatedRowHeight = 50
        shippingTableView.delegate = self
        shippingTableView.dataSource = self
        self.scrollView.contentSize = CGSize(width: self.scrollView.contentSize.width, height: 400)
//        let customView = UIView(frame: CGRect(x: 0, y: 0, width: tableDetails.frame.size.width, height: 50))
//        customView.backgroundColor = UIColor.white
//        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 280, height: 30))
//        button.backgroundColor = UIColor.black
//        button.setTitle("Create a New Addresss", for: .normal)
//        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
//        tableDetails.tableFooterView = customView
//        customView.addSubview(button)
        // Do any additional setup after loading the view.
    }
    func buttonAction(_ sender: UIButton!) {
        print("Button tapped")
    }
    func shippingaddressURL() {
        let url = NSURL(string: self.url)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
            self.shippingArray = (jsonObj!.value(forKey: "address") as? [[String: AnyObject]])!
                OperationQueue.main.addOperation({
                    self.tableDetails.reloadData()
                    let height = (self.shippingArray.count * 165)
                    print(self.shippingArray.count)
                    self.heightConstraint.constant = CGFloat(height)
//                    print(height)
//                    self.scrollView.contentSize = CGSize(width: self.scrollView.contentSize.width, height: (CGFloat(height) + 28 + 28))
//                    print(self.scrollView.contentSize)
                })
            }
        }).resume()
    }
    func shippingmethodURL() {
        let url = NSURL(string: self.urlString)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
                self.arrayss = jsonObj as! [String : AnyObject]
                print(self.arrayss)
                self.keys = jsonObj?.allKeys as! [String]
                print(self.keys)
                OperationQueue.main.addOperation({
                    self.shippingTableView.reloadData()
                    let height = self.arrayss.count * 115
                    print(self.arrayss.count)
                    self.shippingHeightConstraint.constant = CGFloat(height)
                    print(height)
                    print(self.heightConstraint.constant)
                    print(self.scrollView.contentSize)
                })
            }
        }).resume()
    }
    @IBAction func selectRadioButton(_ sender: KGRadioButton) {
        let chekIndex = self.checkIsRadioSelect.index(of: sender.tag)
        _ = self.checkIsButtonEnable.index(of: sender.tag)
        if sender.isSelected {
            shippingTableView.isHidden = false
            titleLabel.isHidden = false
            let height = self.arrayss.count * 115
             self.scrollView.contentSize = CGSize(width: self.scrollView.contentSize.width, height: CGFloat(self.heightConstraint.constant + 56) + CGFloat(height + 31 + 56 + 28 + 28))
        } else{
            if(chekIndex == nil){
                self.checkIsRadioSelect.removeAll(keepingCapacity: false)
                self.checkIsRadioSelect.append(sender.tag)
                self.checkIsButtonEnable.removeAll(keepingCapacity: false)
                self.checkIsButtonEnable.append(sender.tag)
                self.tableDetails.reloadData()
            }
        }
    }


    @IBAction func paymentRadioAction(_ sender: KGRadioButton) {
        let center = sender.center;
        let centralPOint = sender.superview?.convert(sender.center, to:self.shippingTableView )
        let indexPath =  self.shippingTableView.indexPathForRow(at: centralPOint!)

        if sender.isSelected {

        } else{
            chekIndex = indexPath
            selected = true
            self.shippingTableView.reloadData()
        }
    }
    func numberOfSections(in tableView: UITableView) -> Int{
        var count = 0
        if tableView.tag == 100{
            return 1
        }
        else if tableView.tag == 110 {
            return arrayss.count
        }
        return count
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if tableView.tag == 100{
            return "SHIPPING ADDRESS"
        }
        else  {
            return self.keys[section]
        }
    }
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
        if tableView.tag == 100 {
            let header = view as! UITableViewHeaderFooterView
            header.textLabel?.textColor = UIColor.gray
            header.textLabel?.textAlignment = NSTextAlignment.center
            header.textLabel?.font = UIFont(name: "Futura", size: 17)
        }
        else {
            let header = view as! UITableViewHeaderFooterView
            header.tintColor = UIColor.white
            header.textLabel?.textColor = UIColor.darkGray
            header.textLabel?.textAlignment = NSTextAlignment.left
            header.textLabel?.font = UIFont(name: "Futura", size: 17)
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if tableView.tag == 100{
            return shippingArray.count
        }
        else {
            let key = self.keys[section]
            let a :[Any]  = arrayss[key] as! [Any]
            return a.count
        }
    }
    @IBAction func continueButtonAction(_ sender: Any) {
        if selected == false{
            let radiobutton = SCLAlertView()
            _ =  radiobutton.showError("Warning", subTitle: "Please select shipping method", closeButtonTitle: "OK")

        }else{
            let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
            let nextViewController = storyBoard.instantiateViewController(withIdentifier: "payment") as! PaymentMethodViewController
            self.present(nextViewController, animated:true, completion:nil)
        }
    }

    @IBAction func deleteAction(_ sender: UIButton) {
        shippingArray.remove(at:sender.tag)
        self.tableDetails.reloadData()
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView.tag == 100{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AddressTableViewCell
            tableDetails.isHidden = false
            myActivityIndicator.stopAnimating()
            let arr = shippingArray[indexPath.row]
            cell.deleteButton.tag = indexPath.row
            cell.nameLabel.text = arr["name"] as? String
            cell.addressLabel.text = arr["address"]as? String
            let mobilenumber : Any =  arr["number"] as AnyObject
            cell.mobileNumberLabel.text = "\(mobilenumber)"
            cell.radioButton.tag = indexPath.row
            cell.editButton.tag = indexPath.row
            cell.deleteButton.tag = indexPath.row
            cell.editButton.isHidden = true
            cell.deleteButton.isHidden = true
            let checkIndex = self.checkIsRadioSelect.index(of: indexPath.row)
            if(checkIndex != nil){
                shippingTableView.isHidden = false
                tableDetails.isScrollEnabled = false
                scrollView.isScrollEnabled = true
                titleLabel.isHidden = false
                cell.radioButton.isSelected = true
                cell.editButton.isHidden = false
                cell.deleteButton.isHidden = false
            }else{
                cell.radioButton.isSelected = false
                cell.editButton.isHidden = true
                cell.deleteButton.isHidden = true
            }
            return cell
        }
        else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "shippingCell", for: indexPath) as! ShippingMethodTableViewCell
            let key = self.keys[indexPath.section]
            var a :[Any]  = arrayss[key] as! [Any]
            var dictionary = a[indexPath.row] as! [String:Any]
            let name = dictionary["name"]
            let price = dictionary ["price"]
            cell.methodNameLabel.text = name  as? String
            cell.priceLabel.text = price as? String
            if chekIndex == indexPath {
                cell.radioButton.isSelected = true
            } else {
                cell.radioButton.isSelected = false
            }
            return cell
        }
    }

2 个答案:

答案 0 :(得分:2)

您可以将逻辑划分为

  1. 让A和B分别从你的第1和第2个网址中检索json数据。

  2. 在数组中添加A和B.假设dataArray = [A,B]

  3. numberOfSections中的
  4. 返回dataArray.count

  5. numberOfRowsInSection中的
  6. 返回dataArray [section] .count

  7. 最后,您可以创建多个自定义单元格,并在tableview中相应地使用它们

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    switch(indexPath.section)  {
    case 0:{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AddressTableViewCell
            return cell 
           }
    case 1:{
            let cell = tableView.dequeueReusableCell(withIdentifier: "shippingCell", for: indexPath) as! ShippingMethodTableViewCell
            return cell 
           }
    Default:{
            //Default settings
           }
       }
    }
    

答案 1 :(得分:0)

只需在自定义tableviewCell中创建两个函数即。 loadDataOne(data:JSON)loadDataTwo(data:JSON)并在您的自定义TableViewCell中调用这些方法

var dataOne:JSON!{
        didSet{
            loadDataOne()
        }
    }