swift: показывать только заголовки разделов, если их более 1 - PullRequest
0 голосов
/ 04 июля 2019

У меня есть таблица с переменным количеством разделов. Если есть более одного раздела, я хочу показать показ пользовательских заголовков, но если есть только один, мне вообще не нужен заголовок. Мой подход заключается в использовании func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? и возвращении nil, если у меня есть только один раздел. Но вместо того, чтобы не показывать заголовок, я получаю пустой заголовок. Есть идеи?

вот мой код

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Orders"

    tableView.dataSource = self
    tableView.delegate = self


    let headerNib = UINib.init(nibName: "SectionHeader", bundle: Bundle.main)
    tableView.register(headerNib, forHeaderFooterViewReuseIdentifier: "SectionHeader")

}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if(ordersList.count < 2) {return nil}
    let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! SectionHeader
    headerView.label.text = "\(sectionHeaders[section]) (\(ordersList[section].count))"
    headerView.button.setTitle(self.collapsed[section] ? "▶" : "▼", for: .normal)
    headerView.onTap = {
        self.collapsed[section] = !self.collapsed[section]
        headerView.button.rotate(self.collapsed[section] ? CGFloat(-.pi/2.0) : CGFloat(.pi/2.0), duration: 0.1, completion: {
            self.tableView.beginUpdates()
            self.tableView.reloadSections([section], with: .fade)

            self.tableView.endUpdates()
        })
    }

    return headerView
}

Ответы [ 4 ]

0 голосов
/ 04 июля 2019

Используйте tableView.numberOfSections, чтобы получить счетчик секций .И используйте это значение в tableView(_:viewForHeaderInSection:), чтобы проверить, хотите ли вы вернуть SectionHeader или nil.Вам нужно вернуть nil, если вы не хотите показывать header в определенном section.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    guard tableView.numberOfSections > 1 else {
        return nil
    }
    let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! SectionHeader
    //add rest of the code...
    return headerView
}

Реализуйте tableView(_:heightForHeaderInSection:), чтобы вернуть header height на основе section.Верните 0, если вы не хотите показывать header в section, иначе потребуется default header height.

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return (tableView.numberOfSections > 1) ? 100.0 : 0.0
}
0 голосов
/ 04 июля 2019

также используйте метод делегата heightForHeaderInSection.Сделайте высоту 0, если условие не удовлетворяет.Для справки -

public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if(ordersList.count < 2) {return 0.1}
    else { return HEIGHT} //custom value of view height
}
0 голосов
/ 04 июля 2019

Для достижения желаемого результата необходимо использовать следующие методы:

func numberOfSections(in tableView: UITableView) -> Int {
        if(ordersList.count < 2) {return nil}
        return ordersList.count
    }

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if(ordersList.count < 2) {return nil} 
      //else return some view }


func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if(ordersList.count < 2) {return 0}
         return some_height

    }
0 голосов
/ 04 июля 2019

Вы должны переопределить метод numberOfSections для tableview. И вы не должны использовать dequeueReusableHeaderFooterView для представления заголовка раздела. Представления заголовка раздела должны быть пользовательским представлением.

- число секций

func numberOfSections(in tableView: UITableView) -> Int {
    return sectionCount
}

- sectionHeaderView

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    // you can store data on a view model
    let cellViewModel = viewModel.returnViewModel(index: section)

    switch cellViewModel.type {
    case .sampleViewModel1:
        return UIView() // sampleView1
    case .sampleViewModel2:
        return UIView() // sampleView2
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...