Как настроить раздел ячейки - PullRequest
0 голосов
/ 08 февраля 2019

Есть ли способ настроить раздел ячейки?Вероятно, самый простой способ - создать ячейку в раскадровке, но я не знаю, как реализовать ее в своем коде.

Это то, что я до сих пор получил.Это довольно простой и скопированный из учебника на YouTube.Поэтому sectionData должен быть заменен вводом для настроенного раздела / subCell.

Верхняя ячейка должна быть 'mainCell', а ячейка ниже должна отображаться после прикосновения к mainCell

import UIKit

struct cellData {
var opened = Bool()
var title = String()
var sectionData = [String]()
}

class ViewController: UITableViewController {

var tableViewData = [cellData]()


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    tableViewData = [cellData(opened: false, title: "Title1", sectionData: ["Cell1","Cell2","Cell3"]),
                     cellData(opened: false, title: "Title2", sectionData: ["Cell1","Cell2","Cell3"]),
                     cellData(opened: false, title: "Title3", sectionData: ["Cell1","Cell2","Cell3"]),
                     cellData(opened: false, title: "Title4", sectionData: ["Cell1","Cell2","Cell3"])]
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return tableViewData.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableViewData[section].opened == true {
        return tableViewData[section].sectionData.count + 1
    } else {
        return 1
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let dataIndex = indexPath.row - 1

    if indexPath.row == 0  {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {return UITableViewCell()}
        cell.textLabel?.text = tableViewData[indexPath.section].title
        return cell
    } else {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {return UITableViewCell()}
        cell.textLabel?.text = tableViewData[indexPath.row].sectionData[dataIndex]
        return cell
    }
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.row == 0 {
        if tableViewData[indexPath.section].opened == true {
            tableViewData[indexPath.section].opened = false
            let sections = IndexSet.init(integer: indexPath.section )
            tableView.reloadSections(sections, with: .none)
        } else {
            tableViewData[indexPath.section].opened = true
            let sections = IndexSet.init(integer: indexPath.section )
            tableView.reloadSections(sections, with: .none)
        }
    }

}
}

1 Ответ

0 голосов
/ 08 февраля 2019

https://www.appcoda.com/expandable-table-view/

Вы можете следовать этому руководству.Вы можете перезагрузить ячейку, которую хотите расширить, используя приведенный ниже код.Я добавил в `didSelectRowAt.Установите для переменной expandCell значение true для изменения высоты ячейки при перезагрузке.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

     // Expand View 
     self.expandCell = true 
     self.tableView.beginUpdates()
     self.tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
     self.tableView.endUpdates()
 }

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.row == expandRowIndex && self.expandCell {
          return 200
    }
    return UITableViewAutomaticDimension
 } 

, но заданный вопрос не имеет отношения к тому, который вы хотите реализовать.В любом случае, ответ на ваш вопрос заключается в том, что вы можете реализовать viewForHeaderInSection и viewForFooterInSection, чтобы настроить разделы таблицы.

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let cell = "create your custom cell here or you can init from your nib"
        return cell
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 60
}

Если вы хотите сделать это в раскадровке, просто перетащите UITableViewCell в ваше табличное представление, назначьте некоторый reuserIdentifier.вызовите эту ячейку таблицы в вашем viewForHeaderInSection

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