(Swift) Как скрыть некоторые разделы в tableView при включенном тумблере? - PullRequest
0 голосов
/ 26 февраля 2020

У меня есть 5 разделов tebleView, код для каждого из них практически одинаков. Основное отличие заключается в cell.labelCell.text:

CellForRow метод:

let cell = tableView.dequeueReusableCell(withIdentifier: "ToggleTableViewCell", for: indexPath) as! ToggleTableViewCell
            cell.cellSwitch.setOn(false, animated: false)

            switch (indexPath.section, indexPath.row) {
            case (1,0):
                cell.labelCell.text = "Section 1"

                cell.callback = { [unowned self] check in
                    UIView.transition(with: tableView,
                                      duration: 0.5,
                                      options: .showHideTransitionViews,
                                      animations: { self.tableView.reloadData() })
                }

класс ячейки:

class ToggleTableViewCell: UITableViewCell {

    @IBOutlet weak var labelCell: UILabel!

    @IBOutlet weak var cellSwitch: UISwitch!

    var callback:((Bool) -> Void)?

    @IBAction func toggleSwitch(_ sender: Any) {
        if cellSwitch.isOn == true {
            callback?(true)
        }
        else {
            callback?(false)
        }
    }
}

Вопрос: Если я есть 5 таких разделов, и я хочу скрыть, например, первый, когда toggleSwitch включен в последнем, возможно ли это сделать?

Ответы [ 2 ]

1 голос
/ 26 февраля 2020

Подход:

В вашем Model вы можете создать свойство isHidden, которое будет отслеживать, должен ли раздел быть скрытым или нет, т.е.

class Model {
    var sectionName: String
    var isHidden = false

    init(sectionName: String) {
        self.sectionName = sectionName
    }
}

Теперь измените методы UITableViewDataSource на

class VC: UIViewController, UITableViewDataSource, UITableViewDelegate {
    let arr = [Model(sectionName: "Section 1"), Model(sectionName: "Section 2"), Model(sectionName: "Section 3"), Model(sectionName: "Section 4"), Model(sectionName: "Section 5")]
    lazy var dataSource = self.arr

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
        cell.cellSwitch.setOn(false, animated: false)
        cell.labelCell.text = dataSource[indexPath.section].sectionName
        cell.callback = {[weak self] in
            guard let `self` = self else {
                return
            }
            self.arr[indexPath.section].isHidden = !(self.arr[indexPath.section].isHidden)
            self.dataSource = self.arr.filter({ !$0.isHidden })
            tableView.reloadData()
        }
        return cell
    }
}

И вы можете просто вызвать замыкание callback?() в toggleSwitch(_:), и сокрытие / скрытие будет выполнено автоматически.

class TableViewCell: UITableViewCell {
    @IBOutlet weak var labelCell: UILabel!
    @IBOutlet weak var cellSwitch: UISwitch!

    var callback:(()->())?
    @IBAction func toggleSwitch(_ sender: Any) {
        callback?()
    }
}
0 голосов
/ 26 февраля 2020

Я не знаю, что вы хотите отобразить, но если вопрос " Можете ли вы показать / скрыть раздел таблицыView ", ответ будет ДА

Чтобы это работало, вам нужно отделить ваш вид от данных, которые вы хотите отобразить

// let this be declared somewhere
// assume that the top array will be the number of section and inner one will be number fo rows
var tableData: [[String]] = [["1","2","3"], ["4","5","6"], ["7","8","9"], ["10","11","12"], ["13","14","15"]]

// tableView dataSource

func numberOfSections(in collectionView: UICollectionView) -> Int {
   return tableData.count
}

func tableView( _ tableView: UITableView, numberOfRowsInSection section: Int ) -> Int {
   return tableData[section].count
}

func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath ) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: "ToggleTableViewCell", for: indexPath) as! ToggleTableViewCell
   cell.cellSwitch.setOn(false, animated: false)
   let data = tableData[indexPath.section]
   cell.labelCell.text = data[indexPath.row]
   cell.callback = { [unowned self] check in 
      //removes the data from the selection section
      // so if you remove section 2, ["7","8","9"] will be remove
      // atm, it just removes but when you decide what you actually want to do then you can play around and implement a toggling action
      tableData.remove(at: indexPath.section)
      UIView.transition(with: tableView,
                        duration: 0.5,
                        options: .showHideTransitionViews,
                        animations: { self.tableView.reloadData() })
   }
}



...