始终将 cell 保持在 uitableview 的顶部
Always keep cell on the top of uitableview
我有一个基于视图的应用程序,我正在添加一个 uitableview 作为主视图的子视图。 uitableview 充满了 class 类别单元格。一切正常,但我希望“快速笔记”类别始终位于 uitableview 的顶部。这意味着当我在数组中重新加载数据()时,“快速笔记”始终具有索引 0,并且它位于 uitableview 的底部。当我创建新的 cell 时,我需要将它放在“快速笔记”部分下。
请帮助我,我需要什么代码来实现该功能以及我需要把它放在哪里。谢谢!
编辑:
这就是我将“快速笔记”添加到 Realm 数据库的地方。
private let categories = try! Realm()
private init() {
if categories.objects(Category.self).isEmpty {
createCategoryWith(title: "Quick Notes", color: "#FF0000", icon: "quickNotes")
}
}
更新ViewController中的数组:
func didCreateCategory(category: Category) {
RealmHandler.shared.createCategoryWith(title: category.title, color: category.color, icon: category.icon)
self.categories = RealmHandler.shared.getAllCategories()
tableView.reloadData()
}
DataSourceDelegate:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath)
cell.textLabel?.text = categories[categories.count - (1+indexPath.row)].getTitle()
cell.contentView.backgroundColor = hexStringToUIColor(hex: categories[categories.count-(1+indexPath.row)].getColor())
return cell
}
使用viewForHeaderInSection
tableView 的委托方法。
tableView(_ tableView: UITableView, viewForHeaderInSection section: Int)
在这里您可以定义您的 header 单元格。
然后实现您要在此单元格上显示什么的逻辑。
此 headerCell 将始终位于您的 tableView 之上。
我有一个基于视图的应用程序,我正在添加一个 uitableview 作为主视图的子视图。 uitableview 充满了 class 类别单元格。一切正常,但我希望“快速笔记”类别始终位于 uitableview 的顶部。这意味着当我在数组中重新加载数据()时,“快速笔记”始终具有索引 0,并且它位于 uitableview 的底部。当我创建新的 cell 时,我需要将它放在“快速笔记”部分下。 请帮助我,我需要什么代码来实现该功能以及我需要把它放在哪里。谢谢!
编辑: 这就是我将“快速笔记”添加到 Realm 数据库的地方。
private let categories = try! Realm()
private init() {
if categories.objects(Category.self).isEmpty {
createCategoryWith(title: "Quick Notes", color: "#FF0000", icon: "quickNotes")
}
}
更新ViewController中的数组:
func didCreateCategory(category: Category) {
RealmHandler.shared.createCategoryWith(title: category.title, color: category.color, icon: category.icon)
self.categories = RealmHandler.shared.getAllCategories()
tableView.reloadData()
}
DataSourceDelegate:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath)
cell.textLabel?.text = categories[categories.count - (1+indexPath.row)].getTitle()
cell.contentView.backgroundColor = hexStringToUIColor(hex: categories[categories.count-(1+indexPath.row)].getColor())
return cell
}
使用viewForHeaderInSection
tableView 的委托方法。
tableView(_ tableView: UITableView, viewForHeaderInSection section: Int)
在这里您可以定义您的 header 单元格。 然后实现您要在此单元格上显示什么的逻辑。 此 headerCell 将始终位于您的 tableView 之上。