Search code examples
swiftuitableviewheadernstableheaderview

Access each header and controls in the tableview in swift


I have a UITableView with customized header. In that header I have a button with image.

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

    let cView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 40))

    itemNumBtn = UIButton(frame: CGRectMake(0, 0, 70, 42))
    itemNumBtn.setBackgroundImage(UIImage(named: "hide.png"), forState: .Normal)
    cView.addSubview(itemNumBtn)

    return cView
}

I have five header secion.

in separate function how can get the image of the each button, need to access each button

Ex:

fun getHeader() {
    // how to access each header and buttons
    var eachBtn = each button in the header
    var image = all the images of all header section
}

Thanks in advance


Solution

  • In order to get button and image from header, you can implement a customized UIView for header, like

    class HeaderView: UIView {
        var button: UIButton
        var image: UIImage
    
        func init() {
            ...
        }
    } 
    

    And return this HeaderView in your tableView(tableView: UITableView, viewForHeaderInSection section: Int) callback.

    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return HeaderView()
    }
    

    Then use tableView.headerViewForSection(section:) to get 5 customized headers view.

    func getHeaders() {
    
        for index in 1...5 {
             let header = tableView.headerViewForSection(section: index) as! HeaderView
             let button = header.button
             let image = header.image
        }
    }