Home > Enterprise >  How to call button in TableView header section in other files and/or functions in Swift?
How to call button in TableView header section in other files and/or functions in Swift?

Time:07-16

I've been having trouble figuring out a way to send the TableView section where my button is located into another file, where my action handler is located. My button is in the first header section of my tableview. More specifically, I'm not sure how to store the section and send it to other files where I can use it to trigger certain actions for only the button in my SectionHeaderView. Would I need to create a function/delegate and pass in the section and hear? Below are the files I'm using for this.

TableView file

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    guard let vM = suggestionSections[safeIndex: section] else { return nil }
    let header = SectionHeaderView(frame: .zero)
    header.configure(vM)
    header.delegate = delegate
    if section == 0 { // where my button is located (i have two headers)
        // want to send the section to SectionHeaderView file where I have my action func for when the button is tapped...
        // ... or to other files where I have delegates
    }
    return header
}

SectionHeaderView file

lazy var button = UIButton()

CodePudding user response:

Well you can add a property to SectionHeaderView & assign a value to that property in your viewForHeaderInSection:

var section: Int? // in SectionHeaderView

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    guard let vM = suggestionSections[safeIndex: section] else { return nil }
    let header = SectionHeaderView(frame: .zero)
    header.configure(vM)
    header.delegate = delegate
    header.section = section //here
    if section == 0 { // where my button is located (i have two headers)
    // want to send the section to SectionHeaderView file where I have my action func for when the button is tapped...
    // ... or to other files where I have delegates
    }
    return header
}
  • Related