我想為 3 個部分 ["Managers","Accountants","Receptionist"] 分配記錄或單元格,其中鍵 "authority" 驗證了它屬于哪個部分..
SWIFT代碼:
struct GlobalVariables {
static var userdetailsJSON: [JSON] = [JSON.null]
static var sectionTitles: [String] = ["Managers","Accountants","Receptionist"]
}
@IBAction func Userdb_Btn(_ sender: Any) {
let url = "http://.../GetUsers.php"
let headers: HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
let data: Parameters = ["Authorization":"IOSAPP"]
AF.request(url, method: .post, parameters: data, encoding: URLEncoding.default, headers: headers).response { response in
switch response.result {
case .success:
let json : JSON = JSON(response.data ?? JSON.null)
let jsonError = json["error"].boolValue
if jsonError == false{
UsersdbVC.GlobalVariables.userdetailsJSON = json["userDetails"].arrayValue
print(UsersdbVC.GlobalVariables.userdetailsJSON)
}else{
self.displayAlert(title: "Failed to load users data !", message:"")
}
case .failure(let error):
self.displayAlert(title: "Connection error", message: "\(error)")
}
}
}
這是我的 Json 輸出:
[{
"name" : "Oliver",
"password" : "1234",
"username" : "Ramy",
"id" : 84560,
"authority" : "Manager"
}, {
"name" : "Maxwell",
"password" : "1234",
"username" : "Omar",
"id" : 84561,
"authority" : "Accountant"
}, {
"name" : "Tom",
"password" : "1234",
"username" : "Ahmed",
"id" : 84562,
"authority" : "Accountant"
}]
部分的數量可以通過以下方式確定:
func numberOfSections(in tableView: UITableView) -> Int {
return GlobalVariables.sectionTitles.count}
但是我們如何通過從關鍵“權威”驗證自身來填充每個部分的記錄 .. ?讓我解釋一下,我應該在 tableview 中看到如下:
Section: Manager
Cell: ID: 84560 - Oliver
Section: Accountant
Cell: ID:84561 - Maxwell
Cell: ID:84562 - Tom
Section: Receptionist
Cell: Empty...
就像按權限過濾或排序一樣...雖然,以下代碼填充了記錄,但每個部分都相同... CellForRowAt:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "usersTVC", for: indexPath)
let userID: String = GlobalVariables.userdetailsJSON[indexPath.row]["id"].stringValue
let userName: String = GlobalVariables.userdetailsJSON[indexPath.row]["name"].stringValue
cell.textLabel?.text = "ID: \(userID) - \(userName)"
return cell
}
numberOfRowsInSection:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return GlobalVariables.userdetailsJSON[section]["authority"].count
}
任何幫助,將不勝感激 !
uj5u.com熱心網友回復:
忘SwiftyJSON了,這是一個很棒的圖書館,但它已經過時了。
并且忘記將具有靜態屬性的結構作為資料源。
解碼 JSON Decodable- AlamoFire 確實支持它 - 并將陣列分組Dictionary(grouping:by:)為多個部分。
首先創建兩個結構,一個用于部分的結構,一個用于專案(User在以下示例中)
struct Section {
let name : String
let users : [User]
}
struct User : Decodable {
let name, password, username, authority : String
let id : Int
}
這是一個沒有AF的獨立解決方案,創建一個資料源陣列
var sections = [Section]()
解碼 JSON
let jsonString = """
[{
"name" : "Oliver",
"password" : "1234",
"username" : "Ramy",
"id" : 84560,
"authority" : "Manager"
}, {
"name" : "Maxwell",
"password" : "1234",
"username" : "Omar",
"id" : 84561,
"authority" : "Accountant"
}, {
"name" : "Tom",
"password" : "1234",
"username" : "Ahmed",
"id" : 84562,
"authority" : "Accountant"
}]
"""
do {
let users = try JSONDecoder().decode([User].self, from: Data(jsonString.utf8))
let grouped = Dictionary(grouping: users, by: \.authority)
sections = grouped.map(Section.init)
print(sections)
} catch {
print(error)
}
資料源方法是
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "usersTVC", for: indexPath)
let user = sections[indexPath.section].users[indexPath.row]
cell.textLabel?.text = "ID: \(user.id) - \(user.name)"
return cell
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/420065.html
標籤:
