Adding UIButton to UITableView section header

前端 未结 7 1131
一个人的身影
一个人的身影 2021-02-01 20:20

I have a UITableView with 1 section and for the section header, I would like to keep everything about the header the same but simply add a button on the right side.

相关标签:
7条回答
  • 2021-02-01 21:11

    If you are interested in Swift solution:

    override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    
        let frame = tableView.frame
    
        let button = UIButton(frame: CGRectMake(5, 10, 15, 15))  // create button
        button.tag = section 
        // the button is image - set image
        button.setImage(UIImage(named: "remove_button"), forState: UIControlState.Normal)  // assumes there is an image named "remove_button"
        button.addTarget(self, action: #selector(TestController.remove(_:)), forControlEvents: .TouchUpInside)  // add selector called by clicking on the button
    
        let headerView = UIView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))  // create custom view
        headerView.addSubview(button)   // add the button to the view
    
        return headerView   
    }
    

    You might want to specify the height of the header in the section. This must be in sync with the height of the custom view:

    override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat(30)
    }
    
    0 讨论(0)
提交回复
热议问题