How to add image to UITableView section header using swift?

In my willDisplayHeaderView, I changed the color of the section title. But I want to add an image before the section title. Any help? My code for willDisplayHeaderView

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as UITableViewHeaderFooterView header.contentView.backgroundColor = UIColor(red: 238/255, green: 168/255, blue: 15/255, alpha: 0.8) header.textLabel.textColor = UIColor.whiteColor() header.alpha = 1 } 
+8
ios uitableview swift
source share
6 answers

You can create your own title, for example, create a custom cell in the form of a table. Or you can simply add an image as follows:

 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 the UILabel section name as another subset.

+8
source share

Just add the following code to 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 
+6
source share

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 } 
+4
source share

Here we can add a custom title to the 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) } 
+3
source share

I use this method below in my project.

 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 } 
+3
source share

It will work with fast 4

 override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerImage: UIImage = UIImage(named: "image")! let headerView = UIImageView(image: headerImage) return headerView } 
+1
source share

All Articles