这里我在网址中有两个数组,我需要显示如图below所示,我不知道如何在表格视图中实现这一点,如图所示
{
"Flat": [
{
"price": "$5.00",
"id": 11,
"name": "Fixed"
}
],
"United Parcel Service": [
{
"price": "$109.12",
"id": 1,
"name": "worldwide Expedited"
},
{
"price": "$120.18",
"id": 2,
"name": "worldwide Express saver"
}
]
}
class shippingObject: NSObject {
var id :NSInteger!
var name :String!
var price : String!
}
class CheckoutViewController:
UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var ContinueButton: UIButton!
@IBOutlet weak var newAddress: UIButton!
@IBOutlet var tableDetails: UITableView!
@IBOutlet weak var shippingTableView: UITableView!
@IBOutlet weak var HeightConstraint: NSLayoutConstraint!
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 detailsArray : [shippingObject] = []
var shippingArray :[[String: AnyObject]] = []
var price = [String]()
var keys = [String]()
var name = [String]()
var methodArray : [[String: AnyObject]] = []
let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
var arrayss = [String:Any]()
var checkIsRadioSelect = [Int]()
var checkIsButtonEnable = [Int]()
var checkIsPaymentRadioSelect = [Int]()
let response : [Int] = []
override func viewDidLoad() {
super.viewDidLoad()
tableDetails.isHidden = true
shippingTableView.isHidden = true
scrollView.isScrollEnabled = false
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.shippingmethodURL()
self.shippingaddressURL()
tableDetails.delegate = self
tableDetails.dataSource = self
tableDetails.rowHeight = UITableViewAutomaticDimension
tableDetails.estimatedRowHeight = 300
shippingTableView.delegate = self
shippingTableView.dataSource = self
shippingTableView.rowHeight = UITableViewAutomaticDimension
shippingTableView.estimatedRowHeight = 300
// Do any additional setup after loading the view.
}
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()
})
}
}).resume()
}
func assignValuesToObjecs(arrayvalues: NSArray){
(arrayvalues as NSArray).enumerateObjects({ (object, count, stop) in
let Object :shippingObject = shippingObject()
Object.name = (object as AnyObject) .value(forKey: "name") as! String
Object.id = (object as AnyObject) .value(forKey: "id") as! NSInteger
Object.price = (object as AnyObject).value(forKey: "price")as! String
self.detailsArray.append(Object)
})
}
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 { print(jsonObj!)
self.arrayss = jsonObj as! [String : Any]
print(self.arrayss)
//self.shippingArray = (jsonObj!.value(forKey: "Flat") as? [[String: AnyObject]])!
self.assignValuesToObjecs(arrayvalues :(jsonObj?["Flat"] as? [[String: AnyObject]]! as? NSArray)!)
self.assignValuesToObjecs(arrayvalues :(jsonObj?["United Parcel Service"] as? [[String: AnyObject]]! as? NSArray)!)
self.methodArray = (jsonObj!.value(forKey: "United Parcel Service") as? [[String: AnyObject]])!
OperationQueue.main.addOperation({
self.keys = ["Flat","United Parcel Service"]
self.shippingTableView.reloadData()
})
}
}).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
scrollView.isScrollEnabled = true
titleLabel.isHidden = false
} 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()
}
}
}
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 {
var key = self.keys[section]
print(key)
var a :[Any] = arrayss[key] as! [Any]
return a.count
}
}
@IBAction func continueButtonAction(_ sender: Any) {
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 : Int = arr["number"] as! Int
cell.mobileNumberLabel.text = String(describing: 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
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 arr = detailsArray[indexPath.row]
// cell.methodNameLabel.text = arr.name
// cell.priceLabel.text = arr.price
var key = self.keys[indexPath.section]
print(key)
var a :[Any] = arrayss[key] as! [Any]
var dictionary = a[indexPath.row];
cell.methodNameLabel.text = dictionary ["name"] + dictionary ["price"]
return cell
}
}
任何帮助都会非常值得赞赏
答案 0 :(得分:0)
分段UITableView可以帮助您摆脱这种情况。我假设arrayss为字典和jsonObj。
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var key= self.keys[section]
print(key)
var a :[Any] = arrayss[key] as! [Any]
return a.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2 // if not fixed self.keys.count or self.arrayss.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
var key= self.keys[indexPath.section]
print(key)
var a :[Any] = arrayss[key] as! [Any]
var dictionary = a[indexPath.row] as! [String:Any];
cell.textLabel.text = dictionary ["name"]+ dictionary ["price"] // you can set the text from the data model
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.keys[section]
}
----编辑----
为了从字典中单独获取字典的所有键和值。
var key = Array(arrayss.keys).sorted(by: >)
var values = Array(arrayss.values).sorted(by: >)
希望它有所帮助。快乐编码!!