繁体   English   中英

如何使用 SwiftyJSON 在表格视图中填充三个部分

[英]How do i populate three sections in a tableview with SwiftyJSON

我想为 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 output:

[{
  "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
   }

任何帮助,将不胜感激 !

忘记SwiftyJSON ,它是一个很棒的库,但它已经过时了。
并且忘记一个具有 static 属性作为数据源的结构。

使用 Decodable 解码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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM