Использовать результаты запроса области в качестве заголовков раздела UITableView - PullRequest
1 голос
/ 31 января 2020

Я пытаюсь использовать результаты запроса области как заголовки разделов в UITableView.

Классы области:

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

Мой код:

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)
    }

}

Количество разделов работает отлично, но заголовки разделов не заполнены.

Если я добавлю:

print(Array(categoryNames))

в функцию getCategoryNames, она возвращает ["Category 1", "Category 2" , «Категория 3», «Категория 4»] несколько раз. Кажется, это правильный формат для строки, которая требуется для заголовков разделов, но заголовок таблицы не отображается.

1 Ответ

1 голос
/ 31 января 2020

Попробуйте это:

private func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    let nameArr = getCategoryNames()
    return nameArr[section]
}

Функция: fun c tableView (_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? поэтому вам нужно вернуть строку для определенного раздела.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...