Как связать заголовок UITableView, а также хотите показать или скрыть ячейки табличного представления, программно щелкая заголовок табличного представления в swift

Я хочу добавить представление в tableView header, Я уже пробовал разными способами, но достиг цели. Мой код приведен ниже для добавления представления в headerView,

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return arrSupport[section]
}

func tableView(_ tableView: UITableView, willDisplayHeaderView view:UIView, forSection: Int) {
    if let tableViewHeaderFooterView = view as? UITableViewHeaderFooterView {
        tableViewHeaderFooterView.textLabel?.textColor = UIColor.white
        tableViewHeaderFooterView.textLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        tableViewHeaderFooterView.contentView.backgroundColor = UIColor(red: 39.0 / 255.0, green: 41.0 / 255.0, blue: 53.0 / 255.0, alpha: 1.0)
        let headerView = UIView()
        headerView.frame = CGRect(x: tblSupport.frame.origin.x-10, y: 10, width: tblSupport.frame.size.width-20, height: 60)
        tableViewHeaderFooterView.contentView.frame = CGRect(x: 10, y: 0, width: tableView.frame.size.width-20, height: 50)
        headerView.addSubview(tableViewHeaderFooterView)
    }
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let headerView = UIView()
    headerView.frame = CGRect(x: tblSupport.frame.origin.x-10, y: 10, width: tblSupport.frame.size.width-20, height: 60)
    headerView.backgroundColor = UIColor(red: 39.0 / 255.0, green: 41.0 / 255.0, blue: 53.0 / 255.0, alpha: 1.0)
    return headerView
}` 

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

Текущее состояние:

Желаемый статус:

2 ответа

Это просто, вы можете достичь этого путем:

  1. Создайте пользовательский вид для заголовка в разделе.
  2. когда пользователь нажимает на кнопку расхода, перезагрузите этот номер раздела строки (вы хотите показать)
  3. при нажатии на кнопку сворачивания перезагрузить раздел и сделать номер строки равным 0

    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 60;
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        let label = UILabel()
        let abutton = UIButton()
        abutton.frame = CGRect(x: tableView.frame.size.width-60, y: 0, width: 40, height: 60)
        abutton.setTitle("^", for: .normal)
        abutton.setTitleColor(.gray, for: .normal)
        abutton.addTarget(self, action: Selector(("collappesAndExpend")), for: .touchUpInside)
        label.frame = CGRect(x: 10, y: 0, width: tableView.frame.size.width, height: 60)
        label.text = "Your Title"
        label.textColor = .gray
        headerView.frame = CGRect(x: 0, y: 10, width: tableView.frame.size.width, height: 60)
        headerView.backgroundColor = UIColor(red: 39.0 / 255.0, green: 41.0 / 255.0, blue: 53.0 / 255.0, alpha: 1.0)
        headerView.addSubview(label)
        headerView.addSubview(abutton)
        return headerView
    }
    
    func collappesAndExpend(_ sender: Any) {
        //Relod you section
    }
    

Прежде всего, чтобы решить вашу первую проблему, вам нужно указать высоту вашего заголовка.

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

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView.init(frame: CGRect.init(x: 10, y: 10, width: tblSupport.frame.width - 20, height: 40)
    headerView.backgroundColor = UIColor(red: 39.0 / 255.0, green: 41.0 / 255.0, blue: 53.0 / 255.0, alpha: 1.0)

    return headerView

}

Теперь для вашего второго выпуска, мы собираемся сделать высоту ячейки минимальной и вызывая beginUpdates() а также endUpdates(), tableview создаст анимацию, заставляющую ваши клетки анимированно сокращаться:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView.init(frame: CGRect.init(x: 10, y: 10, width: tblSupport.frame.width - 20, height: 40)


    let myButton = UIButton.init(frame: headerView.frame)

    myButton.backgroundColor = .clear
    myButton.tag = section
    myButton.addTarget(self, action: #selector(buttonPressed(sender:)), for: .touchUpInside)



    headerView.addSubview(myButton)

    return headerView

}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {


    // add the next if statement

    if indexPath.section == chosenSection {
        return 0.0000001
    }

    return 30 // put your usual cell height here
}


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

var chosenSection = -1

@objc func buttonPressed(sender : UIButton) {


    if chosenSection == sender.tag {
        chosenSection = -1

    } else {
        chosenSection = sender.tag

        tblSupport.beginUpdates()
        tblSupport.endUpdates()
    }

}

Примечание: установка высоты строки в 0 не сделает ее 0, но установит ее в качестве высоты по умолчанию, поэтому я написал 0.000001

Другие вопросы по тегам