Access each header and controls in the tableview in swift

允我心安 提交于 2021-02-10 08:43:14

问题


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


回答1:


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
    }
}


来源:https://stackoverflow.com/questions/33007142/access-each-header-and-controls-in-the-tableview-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!