how to create bar button or UIButton in tableview header in swift 2.2?
do like
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
initially get the frame of your Tableview
let frame: CGRect = tableView.frame
set the frame for UIbutton where is comes in View
let DoneBut: UIButton = UIButton(frame: CGRectMake(100, 0, 200, 50)) //frame.size.width - 60
DoneBut.setTitle("Done", forState: .Normal)
DoneBut.backgroundColor = UIColor.redColor()
if you are using swift 2.2 call the selector as follows
DoneBut.addTarget(self, action: #selector(ViewController.buttonTapped(_:)), forControlEvents: .TouchUpInside)
if you are using swift 2.1 call the selector as follows
DoneBut.addTarget(self, action: Selector("buttonTapped:"), forControlEvents: .TouchUpInside)button.addTarget(self, action: Selector("buttonTapped:"), forControlEvents: .TouchUpInside)
create the UIView reason viewforHeader returns UIView and add button to that subView
let headerView: UIView = UIView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
headerView.addSubview(DoneBut)
return headerView
}
call method like
func buttonTapped(sender: UIButton) {
//Button Tapped and open your another ViewController
}
Updated answer
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let frame: CGRect = tableView.frame
let DoneBut: UIButton = UIButton(frame: CGRectMake(frame.size.width - 200, 0, 150, 50)) //
DoneBut.setTitle("Done", forState: .Normal)
DoneBut.backgroundColor = UIColor.redColor()
DoneBut.addTarget(self, action: #selector(ViewController.buttonTapped(_:)), forControlEvents: .TouchUpInside)
DoneBut.backgroundColor = UIColor.blueColor()
let headerView: UIView = UIView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
headerView.backgroundColor = UIColor.redColor()
headerView.addSubview(DoneBut)
return headerView
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50.0
}
func buttonTapped(sender: UIButton) {
//Button Tapped and open your another ViewController
}
output