UiTableView以编程方式按节组织项目



我试图根据用户的位置对其进行分组。例如,纽约市的任何人都应该在表格视图的NYC部分下,洛杉矶的任何人也应该在该部分下。

//Sets up the sections
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
//Sets the header view
guard let header = view as? UITableViewHeaderFooterView
else {
return
}
//Sets the properties.
view.tintColor = ChatMessageCell.indexedColor
header.textLabel?.textColor = UIColor.white
header.textLabel?.font = UIFont(name: "Open Sans Bold", size: 11)
header.backgroundColor = ChatMessageCell.indexedColor
header.textLabel?.textAlignment = .center
//Sets the variable headerText = to the text labels header
self.headerText = header.textLabel?.text!
}

我创建了一个名为headerText的变量,用于存储页眉的文本标签。在numberOfRowsInSection中,我将用户的位置与标题进行比较。如果它们匹配,我会返回用户,但如果它们不匹配,则不应返回

//Sets the number of rows equal to the amount of Users.
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//Observes the users (Firebase
refHandle = ref.child("Users").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String : AnyObject]{
let user = Users()
user.id = snapshot.key
user.setValuesForKeys(dictionary)

//If statement to see if their location is equal to header it should be under
//This array is empty + meant to store only the users whose location is equal to the section title
if user.location == self.headerText{
return user
}
else{
return 0
}
}
})
}

我认为您的代码有两个问题:

  • 要创建/修改头视图,应该实现viewForHeaderInSection(而不是在willDisplayHeaderView中执行)
  • 您应该而不是以某种方式存储当前标头的状态数据(如headerText)。这在很大程度上取决于表显示标题和单元格的顺序的框架实现细节

因此,您需要不同的方法来访问分组/标头条件和访问单元格数据。

一个微不足道的例子:

  • 首先,您将计算部分/位置(在viewDidLoadviewDidAppear中的某个位置),按字母顺序对它们进行排序,并将它们存储在一个名为locations或不知何故的数组中
  • numberOfRowsInSection中,返回位置数(例如locations.count
  • viewForHeaderInSection中,您将检索属于所提供部分的数据,例如return locations[section]
  • numberOfRowsInSection中,您可以计算属于给定部分的用户数量
  • cellForRow中,您将计算并返回一个包含用户数据的单元格

最新更新