我正在用动态 JSON 数据填充我的 tableView。我设计了自定义 tableviewCell,我隐藏了一个 View 并仅在存在数据时显示。首先,我在 tableView 中显示了所有员工的姓名,稍后当他们被分配到任何项目时,我必须在 DetailsView 中显示项目详细信息,如下所示。
在这里,我在 forLoop 中为 EmployeeList 中的 employeeIds 调用了 projectDetails api。
我将项目详细信息存储在一个数组中,并通过cellForRow 中的projectListArray[indexPath.row]
将值分配给行。但问题是,当某些员工未分配任何项目时,我会收到 Index out of range 错误。 ExpandableCell
将保持折叠状态。希望我到这里为止都清楚。
因此只有分配了项目的员工才会显示 ExpandableCell
展开,对于其他人,单元格将折叠。
public func getEmployeesList(request : EmployeesListRequest) { // api call to get Employees List
// if EmployeeListArray is not till and if response is SUCCESS, give ProjectDetails api call
if response.isSuccess() {
for beds in array {
self.getProjectDetails(request: self.projectDetailsRequest)
//refresh TableView
}
}
}
public func getProjectDetails(request : ProjectDetailsRequest) {
if Network.response(response: response, errorMsg: nil) {
let object = response.obj as? ProjectDetails
if response.isSuccess() {
if response.obj != nil {
self.projectDetailsArray.append(object!)
self.projectEmployeeIdArray.append(object.employeeId!)
}else{
print(“Project Object is nil\n")
}
}
}
}
// In cellForRowAt indexPath
// Displayed Employee names in NamesView now want to display project details
var expandedRows = Set<IndexPath>()
for id in projectEmployeeIdArray {
if employeeId == id {
cell.projectDetailsView.isHidden = false
expandedRows.insert(indexPath)
if !projectDetailsArray.isEmpty{
let sortedData = projectDetailsArray.sorted(by:{$0.employeeId < $1.employeeId}) //since the dictionary was not sorted. //Error if some ids nil
let details = sortedData[indexPath.row] //Error because some employees do not project assigned.
cell.projectLabel.text = details.projectName!
}else{
expandedRows.remove(indexPath)
}
}
}
我也曾尝试过 projectDetailsArray[safe: indexPath.row]
,但未能分配项目项目详细信息。如果索引 0 和 2 有项目详细信息,它将为索引 2 提供 nil 数据。
最佳答案
我强烈建议为您的数据创建一个模型,例如
struct Employee {
var id = ""
var name = ""
var projects = [Project]()
}
struct Project {
var name = ""
}
var model = [Employee]()
如果你有这个,你需要以你喜欢的排序方式将你的 JSON-Response 转换成员工/项目模型。这只需执行一次,而不是在每次 cellForRowAt indexPath
调用中执行
UITableViewDataSource
函数的实现非常简单:
- 在
numberOfSections(in:)
中返回model
中的员工数 - 在
tableView(_:numberOfRowsInSection:)
中,获取给定部门的员工,并返回其项目数 - 在
tableView(_:titleForHeaderInSection:)
中,获取给定部分的员工并返回其名称(或您希望在此处显示的任何内容) - 在
tableView(_:cellForRowAt:)
中,获取给定indexPath.section
的员工,根据indexPath.row获取该员工的项目
并配置单元格
关于arrays - Swift 3/4 - 仅在所需的 tableView 单元格中填充数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50037507/