gpt4 book ai didi

ios - 如何根据 JSON 数组中的字段对表格 View 单元格进行分组

转载 作者:行者123 更新时间:2023-11-29 05:46:03 25 4
gpt4 key购买 nike

本质上,我使用 JSON 数据来创建数组并形成表格 View 。

我希望表格单元格按 JSON 数组中的字段之一进行分组。

JSON 数据如下所示:

[{"customer":"Customer1","number":"122039120},{"customer":"Customer2","number":"213121423"}]

每个号码需要按每个客户分组。

如何做到这一点?

这就是我使用表实现 JSON 数据的方式:

CustomerViewController.swift

import UIKit

class CustomerViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, FeedCustomerProtocol {

var feedItems: NSArray = NSArray()
var selectedStock : StockCustomer = StockCustomer()
let tableView = UITableView()
@IBOutlet weak var customerItemsTableView: UITableView!

override func viewDidLoad() {

super.viewDidLoad()



//set delegates and initialize FeedModel
self.tableView.allowsMultipleSelection = true
self.tableView.allowsMultipleSelectionDuringEditing = true

self.customerItemsTableView.delegate = self
self.customerItemsTableView.dataSource = self

let feedCustomer = FeedCustomer()

feedCustomer.delegate = self
feedCustomer.downloadItems()

}


}


func itemsDownloaded(items: NSArray) {

feedItems = items
self.customerItemsTableView.reloadData()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of feed items

print("item feed loaded")
return feedItems.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

// Retrieve cell

let cell = tableView.dequeueReusableCell(withIdentifier: "customerGoods", for: indexPath) as? CheckableTableViewCell

let cellIdentifier: String = "customerGoods"
let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!

// Get the stock to be shown
let item: StockCustomer = feedItems[indexPath.row] as! StockCustomer
// Configure our cell title made up of name and price


let titleStr = [item.number].compactMap { $0 }.joined(separator: " - ")


return myCell
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark

let cellIdentifier: String = "customerGoods"
let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
myCell.textLabel?.textAlignment = .left


}

}

FeedCustomer.swift:

import Foundation

protocol FeedCustomerProtocol: class {
func itemsDownloaded(items: NSArray)
}


class FeedCustomer: NSObject, URLSessionDataDelegate {



weak var delegate: FeedCustomerProtocol!

let urlPath = "https://www.example.com/example/test.php"

func downloadItems() {

let url: URL = URL(string: urlPath)!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)

let task = defaultSession.dataTask(with: url) { (data, response, error) in

if error != nil {
print("Error")
}else {
print("stocks downloaded")
self.parseJSON(data!)
}

}

task.resume()
}

func parseJSON(_ data:Data) {

var jsonResult = NSArray()

do{
jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray

} catch let error as NSError {
print(error)

}

var jsonElement = NSDictionary()
let stocks = NSMutableArray()

for i in 0 ..< jsonResult.count
{

jsonElement = jsonResult[i] as! NSDictionary

let stock = StockCustomer()

//the following insures none of the JsonElement values are nil through optional binding
if let number = jsonElement[“number”] as? String,
let customer = jsonElement["customer"] as? String,

{

stock.customer = customer
stock.number = number
}

stocks.add(stock)

}

DispatchQueue.main.async(execute: { () -> Void in

self.delegate.itemsDownloaded(items: stocks)

})
}
}

StockCustomer.swift:

import UIKit

class StockCustomer: NSObject {

//properties of a stock

var customer: String?
var number: String?


//empty constructor

override init()
{

}

//construct with @name and @price parameters

init(customer: String) {

self.customer = customer



}



override var description: String {
return "Number: \(String(describing: number)), customer: \(String(describing: customer))"

}

}

最佳答案

您可以通过创建数组数组来实现此目的。所以像这样

[[{"客户": "客户1", "号码": "123"}, {"客户": "客户1", "号码": "456"}], [{"客户": "customer2", "number": "678"}, {"customer": "customer2", "number": "890"}]]

这不是唯一可用于分组的数据结构。另一种可能性是:

{"customer1": [{"customer": "customer1", "number": "123"}, {"customer": "customer1", "number": "456"}], "customer2": [{"customer": "customer2", "number": "678"}, {"customer": "customer2", "number": "890"}]}

然后您可以使用 UITableView sections 按客户进行分组。部分计数将是内部数组的数量,每个部分将包含与该内部数组中的数字一样多的行。

关于ios - 如何根据 JSON 数组中的字段对表格 View 单元格进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56142037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com