Here is the full code.
let sections: [String] = ["Cleaning","Computer Repair", "Electircity", "Painting", "Plumbing"]
let sectionImages: [UIImage] = [picutre1, picture2, picture3, picture4]
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let imageView = UIImageView()
imageView.image = sectionImages[section]
let headerView = UIView()
headerView.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.centerXAnchor.constraint(equalTo: headerView.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: headerView.centerYAnchor).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 60).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 60).isActive = true
return headerView
}
How can I add title in header ?
And, is there another way to set the images autot layout?
Try this one:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let imageView = UIImageView()
imageView.image = sectionImages[section]
let titleLabel = UILabel()
titleLabel.text = sections[section]
titleLabel.font = UIFont.systemFont(ofSize: 17, weight: .bold)
titleLabel.textAlignment = .left
let headerView = UIView()
headerView.addSubview(imageView)
headerView.addSubview(titleLabel)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.leadingAnchor.constraint(equalTo: headerView.leadingAnchor, constant: 20).isActive = true
imageView.centerYAnchor.constraint(equalTo: headerView.centerYAnchor).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 60).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 60).isActive = true
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 20).isActive = true
titleLabel.trailingAnchor.constraint(equalTo: headerView.trailingAnchor, constant: -20).isActive = true
titleLabel.centerYAnchor.constraint(equalTo: headerView.centerYAnchor).isActive = true
return headerView
}