问题
I am trying to use results from a Realm query as section headers in a UITableView.
Realm classes:
class Person: Object {
@objc dynamic var personId = UUID().uuidString
@objc dynamic var firstName: String = ""
@objc dynamic var surname: String = ""
@objc dynamic var mobileNumber: Int = 0
@objc dynamic var password: String = ""
override static func primaryKey() -> String? {
return "personId"
}
}
class Category: Object {
@objc dynamic var categoryId = UUID().uuidString
@objc dynamic var person: Person?
@objc dynamic var categoryName: String = ""
let categoryContent = List<String>()
override static func primaryKey() -> String? {
return "categoryId"
}
}
My code:
class HomeController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let realm = try! Realm()
var itemsInSections: Array<Array<String>> = [["1A"], ["2A"], ["3A"], ["4A"], ["5A"], ["6A"], ["7A"], ["8A"], ["9A"], ["10A"]] //Test content to figure out later
@IBOutlet weak var tableDetails: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableDetails.dataSource = self
tableDetails.delegate = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return getCategoryNames().count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemsInSections[section].count
}
private func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> [String] {
return getCategoryNames()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTableViewCell", for: indexPath)
let text = self.itemsInSections[indexPath.section][indexPath.row]
cell.textLabel!.text = text
return cell
}
func getCategoryNames() -> [String] {
let categoryNames = realm.objects(Category.self).filter("person.mobileNumber == %@", mobileNumber).map({$0.categoryName})
return Array(categoryNames)
}
}
The number of sections works perfectly, but the section headers are blank.
If I add:
print(Array(categoryNames))
to the getCategoryNames function, it returns ["Category 1", "Category 2", "Category 3", "Category 4"] several times. This seems to be the correct format for the string that is required for the section headers, but the table header is not showing.
回答1:
Try this:
private func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let nameArr = getCategoryNames()
return nameArr[section]
}
Function: func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? so you need to return string for a particular section.
来源:https://stackoverflow.com/questions/60000245/use-realm-query-results-as-uitableview-section-headers