In my willDisplayHeaderView I have changed color of section header But I want to add an image before section title. Any help? My code for willDisplayHeaderView is
Simply Add the following code in your viewDidLoad()
method.
var frame = CGRectMake(0, 0, self.view.frame.size.width, 200)
var headerImageView = UIImageView(frame: frame)
var image: UIImage = UIImage(named: "yourImage")!
headerImageView.image = image
youTableView.tableHeaderView = headerImageView
I use this method below in my proj.
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let uilbl = UILabel()
//uilbl.numberOfLines = 0
//uilbl.lineBreakMode = NSLineBreakMode.ByWordWrapping
//uilbl.text = "blablabla"
uilbl.sizeToFit()
uilbl.backgroundColor = UIColor(patternImage: UIImage(named: "yr-img-name")!)
return uilbl
}
Here it is how we can add custom header in UITableView
.
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as UITableViewHeaderFooterView
let imageViewGame = UIImageView(frame: CGRectMake(5, 8, 40, 40));
let image = UIImage(named: "Games.png");
imageViewGame.image = image;
header.contentView.addSubview(imageViewGame)
}
You could design your own header, like you would design a custom cell in a table view. Or you could just add an image like so:
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var myCustomView: UIImageView
var myImage: UIImage = UIImage(named: "myImageResource")
myCustomView.image = myImage
let header: UITableViewHeaderFooterView = view as UITableViewHeaderFooterView
header.addSubview(myCustomView)
return header
}
Then you can simply add your section title UILabel as another subview.
For Swift 3
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.textLabel?.textColor = UIColor.white
let headerImage = UIImage(named: "headerBanner.jpg")
let headerImageView = UIImageView(image: headerImage)
header.backgroundView = headerImageView
}
This will work with swift 4
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerImage: UIImage = UIImage(named: "image")!
let headerView = UIImageView(image: headerImage)
return headerView
}