Как получить номер section по нажатию на header в tableview?


#1

Добрый день.
Подскажите, как узнать номер секции по которой происходит клик в tableView?
В настоящий момент есть такой код
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let header = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! HeaderCell
    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(showAllWorkersInProject))
    header.addGestureRecognizer(tapRecognizer)
    header.projectNameLabel.text = projectsName[section]
    return header
}


@objc func showAllWorkersInProject(){
    print("tapSection")
    if let indexPath = tableView.indexPathForSelectedRow {
        print("tapSection \(section)")
                showDetailProjectId = String(indexPath.section)
        performSegue(withIdentifier: "DetailProjectSegue", sender: nil)
    }
}

Первый принт tapSection отрабатывает нормально, а вот второй нет, что собс-но и логично по идее, т.к. клик происходит по header а не по ячейке.
Вопрос - как узнать номер секции того header, на который тапнули?


#2

Посмотрите на этом ресурсе ролик про делегирование через замыкание. После в вашем кастомном хедере:

var tapHandler: (()->())?

В самом хедере:

@IBAction func headerWasTapped(_ sender: UIButton) {
    tapHandler?()
}

После где создаете хедер, подпишитесь на обработку тапа:

header.tapHandler = {
  // выход произойдет здесь, тем более у метода есть значение section
}

Но вначале изучите материал из обучающего ролика, сможете более сложные вещи делать


#3

Как один из вариантов


#4
class HeaderView: UITableViewHeaderFooterView {
    
    var tapHandler: ((HeaderView) -> Void)!
    
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapAction)))
        print("Hello")
    }
    
    @objc private func tapAction() {
        tapHandler?(self)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.register(HeaderView.self, forHeaderFooterViewReuseIdentifier: "header")
        }
    }
    
    private let items = [
        (name: "Section 1", source: ["A", "B", "C"]),
        (name: "Sectoin 2", source: ["A", "B", "C"])
    ]
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items[section].source.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = items[indexPath.section].source[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return items[section].name
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") as! HeaderView
        header.tapHandler = { [unowned self] _ in
            print(self.items[section].name)
        }
        return header
    }
}

#5

Большое спасибо за помощь =)