How to make multiple level sections in UITableView in Swift 4 - ios

How to make nested table (multiple level sections) in swift 4 like the below picture:
A UITableView is designed to show just two levels (sections and rows), but I want to display more than two levels.

Basic Section and Row.
var titleString = [0 : "Bat and Ball", 1 : "Hockey"]
var rowString = [0: ["Baseball", "Softball", "Cricket"], 1: ["Field Hockey", "Ice Hockey", "Roller Hockey"]]
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (rowString[section]?.count)!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SOTableViewCell
cell.testLbl.text = rowString[indexPath.section]?[indexPath.row]
cell.selectionStyle = .none
return cell
}
// Uncomment for Default design and comment viewForHeaderInSection method
//func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
//return titleString[section]
//}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let sectionView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 25))
sectionView.backgroundColor = UIColor.magenta
let sectionName = UILabel(frame: CGRect(x: 5, y: 0, width: tableView.frame.size.width, height: 25))
sectionName.text = titleString[section]
sectionName.textColor = UIColor.white
sectionName.font = UIFont.systemFont(ofSize: 14)
sectionName.textAlignment = .left
sectionView.addSubview(sectionName)
return sectionView
}

Related

Add a Section Separator Between UITableView

The first one(left) is my design and the second one(right) is what I have achieved still now. One difference is that for the second image I don't have the separator line like the first one. In viewForFooterInSection i have already tried many existing solutions to show separator lines but didn't get the exact solution. I need the separator line at the end of the last row of the first and second sections with some space.
Here is my code -
func numberOfSections(in tableView: UITableView) -> Int {
return secName.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "APHomeTableViewCell", for: indexPath) as! APHomeTableViewCell
cell.selectionStyle = .none
cell.cellTitle.text = items[indexPath.section][indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.secName[section]
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
self.tableView.backgroundColor = UIColor.white
let headerFrame = tableView.frame
let title = UILabel()
title.frame = CGRect(x: 40, y: 0, width: headerFrame.size.width-20, height: 40)
title.font = UIFont.SFBoldFont(ofSize: 14)//UIFont(name: "Futura", size: 30)!
title.text = self.tableView(tableView, titleForHeaderInSection: section)
title.textColor = UIColor(white: 0.19, alpha: 1.0)//UIColor(red: 34/255.0, green: 141/255.0, blue: 183/255.0, alpha: 1.0)
let headerView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: headerFrame.size.width, height: headerFrame.size.height))
headerView.addSubview(title)
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 45
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let section = indexPath.section
return 70
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 50
}
you can do a little change
turn
to

How to use a fixed cell in table and then a list of item below that?

I am using below code for one fixed cell at the top and then list of items in below in a single tableview, I am able to load the data from firestore database, but the first item in from the database is not shown, it is kind of hidden behind the fixed "detailscell", rest the fixed cell and all other items from the database shows up, how to fix that?
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// print(posts)
return posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 && details1.count > 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "detailsCell") as! DetailsCellInHomeScreen
cell.set(details: details1[indexPath.row])
return cell
} else if posts.count > (indexPath.row - 1) {
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.set(post: posts[indexPath.row - 1])
return cell
} else {
return UITableViewCell()
}
}
TableView has a function like below:
// MARK: - Headers and Footers
extension MyTableViewController {
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return MyCustomView()
}
}
You can use this function to return any view you want as a section header. Also note that sectionHeader views are sticky in default style tableView (not grouped style!). So you can use this as a advantage.
There are many tutorials like this one on the internet to follow and learn how to build a custom section section header for UITableView
You should add header on the table view:
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// print(posts)
return posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.set(post: posts[indexPath.row - 1])
return cell
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.width, height: 50))
let label = UILabel()
label.frame = CGRect.init(x: 5, y: 5, width: headerView.frame.width-10, height: headerView.frame.height-10)
label.text = "A Label on detailsCell"
headerView.addSubview(label)
return headerView
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
if the tableView has several section you can realize the section with section: Int object
tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? uses for create the header view and tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat uses for set header height

all of the cells in section view are not being returned

I have my tableview hooked up property to my viewcontroller class however I am unable to get all of my cells to return within the sections. I want 10pix margins between each cell and was able to do this successfully in another VC, however now the method that I am using is only returning one cell (there are only 2 cells total) so I would like help in figuring out a way to display all cells within the section, code is included below:
//UITableViewDataSource
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.layer.cornerRadius = 8.0
headerView.layer.masksToBounds = true
headerView.backgroundColor = UIColor.colorWithHex("A171FF")
let headerLabel = UILabel(frame: CGRect(x: 30, y: 0, width:
tableView.bounds.size.width, height: tableView.bounds.size.height))
headerLabel.font = UIFont(name: "Gill Sans", size: 15)
headerLabel.textColor = UIColor.white
headerLabel.text = self.tableView(self.myWldTbl, titleForHeaderInSection: section)
headerLabel.sizeToFit()
headerView.addSubview(headerLabel)
return headerView
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch (section) {
case 0 :
return userMoves.count
case 1:
return rsvps.count
default :
print("unable to set up sections")
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row % 2 != 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: MyWorldTableViewCell.self)) as! MyWorldTableViewCell
//cell appearance
cell.layer.cornerRadius = 8.0
cell.clipsToBounds = true
//cell data
let evt = userMoves[indexPath.row]
cell.rsvpCount.text = "\(rsvps.count)"
//evt img
if let evtImg = evt.event_photo_url {
cell.img.kf.setImage(with: URL(string: Constants.Server.PHOTO_URL + evtImg))
} else {
cell.img.image = UIImage(named: "user_icon")
}
cell.ttl.text = evt.event_name!
return cell } else {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: InvisibleCell.self)) as! InvisibleCell
cell.backgroundColor = UIColor.clear
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row % 2 == 0 {
return 10.0
}
return 102.0
}
//UITableViewDelegate
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30
}
EDITED:
The first thing that is confusing about your code is that you appear to have 2 sections showing the contents of 2 different arrays (per the logic in numberOfRowsInSection), but you don't check the section number in cellForRowAt.
Before anything else, you should be checking indexPath.section in cellForRowAt to make sure you are using the correct array. As written, your code is using the userMoves array to populate both sections.
The cause of your missing cells is that you must account for the invisible separator cells in your numberOfRowsInSection method. You had the right idea to multiply by 2:
switch (section) {
case 0 :
return userMoves.count * 2
//etc
}
When accessing the array, in cellForRowAt, you need to divide by 2 to avoid the index out of bounds exception:
if indexPath.row % 2 != 0 {
//dequeue, etc.
let evt = userMoves[indexPath.row / 2]
//etc.
}

How to embed text view inside a table view cell having multiple sections?

I am using a table view with multiple section. In one table view cell which is having text label and detailed text label to display array objects. Now I want add a new section, in this section I will be having more text like a paragraph. How to display data in text view?
{
var dataSection01:NSMutableArray = NSMutableArray()
var dataSection02:NSMutableArray = NSMutableArray()
var sectionTitleArray : NSMutableArray = NSMutableArray()
var arrayForBool : NSMutableArray = NSMutableArray()
var sectionContentDict : NSMutableDictionary = NSMutableDictionary()
in viewDidLoad()
sectionTitleArray = ["Assignment Information","Details"]
let tmp1 : NSArray = assignInfoArray
var string1 = sectionTitleArray .objectAtIndex(0) as? String
[sectionContentDict .setValue(tmp1, forKey:string1! )]
let tmp2 : NSArray = detailsInfoArray
string1 = sectionTitleArray .objectAtIndex(1) as? String
[sectionContentDict .setValue(tmp2, forKey:string1! )]
dataSection01 = [ "Name:", "Phone", "Email" so on]
dataSection02 = [ "Address", "Street", "State","ZipCode"]
//mapping like this using object mapper
assignInfoArray.addObject((newDetails?.clientName)!)
assignInfoArray.addObject((newDetails?.clientPhone)!)
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sectionTitleArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let CellIdentifier = "CellRightDetail"
var cell :UITableViewCell?
cell = self.tableView.dequeueReusableCellWithIdentifier(CellIdentifier)
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value2, reuseIdentifier: "CellRightDetail")
}
let manyCells : Bool = arrayForBool .objectAtIndex(indexPath.section).boolValue
if (!manyCells) {
// cell.textLabel.text = #"click to enlarge";
}
else{
let items: NSMutableArray = self.dataFromIndexPath(indexPath)
let content = sectionContentDict .valueForKey(sectionTitleArray.objectAtIndex(indexPath.section) as! String) as! NSArray
cell!.detailTextLabel?.text = content .objectAtIndex(indexPath.row) as? String
cell!.detailTextLabel?.textColor = UIColor.whiteColor()
cell!.textLabel?.textColor = UIColor.whiteColor()
cell!.textLabel?.font = UIFont(name:"Helvetica-Bold", size: 13.0)
cell!.textLabel?.text = items[indexPath.row] as? String
}
return cell!
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if(arrayForBool .objectAtIndex(section).boolValue == true)
{
let tps = sectionTitleArray.objectAtIndex(section) as! String
let count1 = (sectionContentDict.valueForKey(tps)) as! NSArray
return count1.count
}
return 0;
}
func dataFromIndexPath(indexPath: NSIndexPath!) -> NSMutableArray!
{
if (indexPath.section == 0)
{
return dataSection01
}
else if (indexPath.section == 1)
{
return dataSection02
}
return nil
}
}
In storyboard
Blue color is the first cell and green color is my second cell.
You have to create two cell like this and for each cell you have to create different customcell class. Make outlets of UILabel and UITextView in their respective class and use the below code .
May be your requirement vary little bit, so use delegates according to it.
Implement your code like this:
// MARK:- --- TableView Height ---
open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
return 45
}
open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
return 1
}
open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 45
}
open func numberOfSections(in tableView: UITableView) -> Int{
return 2
}
// MARK:- --- TableView tittle ---
open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?{
return "hearder " + String(section)
}
open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
let viewHeader : UIView = UIView(frame: CGRect(x: 0 , y: 64, width: self.view.frame.size.width , height: 45))
viewHeader.backgroundColor = UIColor(red: 180.0/255.0, green: 160.0/255.0, blue: 240.0/255.0, alpha: 1)
let btnHeader : UIButton = UIButton(frame: CGRect(x: 0 , y: 0, width: viewHeader.frame.size.width , height: viewHeader.frame.size.height))
btnHeader.setTitle("section #\(section)", for: UIControlState())
btnHeader.backgroundColor = UIColor.darkGray
btnHeader.isSelected = arrIsExpand[section]
btnHeader.tag = section
btnHeader.addTarget(self, action:#selector(expandMethod(_:)) , for: UIControlEvents.touchUpInside)
viewHeader.addSubview(btnHeader)
return viewHeader
}
// MARK:- --- TableView data source ---
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return 10
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
if(indexPath.section == 0){ // for your first section
let firstCell : MyFirstCustomCell = tableView.dequeueReusableCell(withIdentifier: "firstcell") as! DesignTableCell
firstCell.lblTittle?.text = "Tittle"
firstCell.lblDescription?.text = "Description"
return firstCell
}
//for second section
else{
let secondCell : MySecondCustomCell = tableView.dequeueReusableCell(withIdentifier: "secondcell") as! DesignTableCell
secondCell.lblTittle?.text = "Tittle"
secondCell.txtViewData?.text = "Blah! Blah!"
return secondCell
}
}
May be you face the problem with the row height because I give static height here i.e. 45, so use uiautomaticdimension instead of static 45, and also impliment the delegate estimatedHeightForRow.

Change the sections header background color in UITableView using an array of headers

I have a array of headers that I use
let sectionHeaderTitleArray = ["test1","test2","test3]
and they are showed using
func tableView[tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionHeaderTitleArray[section] as String
}
Now all of this works fine but I would like to modify the background color of the headers so that they are more visible (Darker Color)
any idea if I can do this in a simple line or do I need to use a custom cell to create this
thanks
update
//number of sections and names for the table
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.sectionHeaderTitleArray.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionHeaderTitleArray[section] as String
}
func tableView(tableView: UITableView, ViewForHeaderInSection section: Int) -> UIView? {
return self.tableView.backgroundColor = UIColor.lightGrayColor()
}
If you're using only titleForHeaderInSection :
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
(view as! UITableViewHeaderFooterView).contentView.backgroundColor = UIColor.black.withAlphaComponent(0.4)
(view as! UITableViewHeaderFooterView).textLabel?.textColor = UIColor.white
}
Instead of using the
func tableView(_ tableView: UITableView,titleForHeaderInSection section: Int) -> String?
data source method, you can use the
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
delegate method and simply customize the UIView returned as you wish.
For example set the text of the UILabel textLabel to your desired value and the backgroundColor to the desired UIColor.
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let returnedView = UIView(frame: CGRectMake(x, y, width, height)) //set these values as necessary
returnedView.backgroundColor = UIColor.lightGrayColor()
let label = UILabel(frame: CGRectMake(labelX, labelY, labelWidth, labelHeight))
label.text = self.sectionHeaderTitleArray[section]
returnedView.addSubview(label)
return returnedView
}
SWIFT 5
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let returnedView = UIView(frame: CGRect(x: x, y: y, width: width, height: height)) //set these values as necessary
returnedView.backgroundColor = .white
let label = UILabel(frame: CGRect(x: x, y: y, width: width, height: height))
label.text = self.sectionHeaderTitleArray[section]
returnedView.addSubview(label)
return returnedView
}
You have to keep both
titleForHeaderInSection
AND
viewForHeaderInSection
Here is some working code in Swift 3
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionHeaderTitleArray[section]
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let returnedView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 25))
returnedView.backgroundColor = .lightGray
let label = UILabel(frame: CGRect(x: 10, y: 7, width: view.frame.size.width, height: 25))
label.text = self.sectionHeaderTitleArray[section]
label.textColor = .black
returnedView.addSubview(label)
return returnedView
}
SWIFT 5
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "headerId") as! CustomHeader
let background = UIView(frame: view.bounds, background: .clear)
header.backgroundView = background
return header
}
SWIFT 4
Super easy, by setting header's view, contentView background color..
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "headerId") as! CustomHeader
header.contentView.backgroundColor = AnyColor
return header
}
Swift 5 iOS 13:
//Remove 'override' if you don't override from UITableviewController
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let headerView = view as? UITableViewHeaderFooterView else { return }
headerView.tintColor = .clear //use any color you want here .red, .black etc
}
Swift 4.X
This is tested and working code.
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Total Count (41)"
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = UIColor.lightGray
let header = view as! UITableViewHeaderFooterView
header.textLabel?.textColor = UIColor.darkGray
header.textLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
}
Swift 3+
I used this:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 20))
headerView.backgroundColor = .lightGray
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = stringValues[section]
headerView.addSubview(label)
label.leftAnchor.constraint(equalTo: headerView.leftAnchor).isActive = true
label.rightAnchor.constraint(equalTo: headerView.rightAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: headerView.centerYAnchor).isActive = true
label.heightAnchor.constraint(equalToConstant: 25).isActive = true
return headerView
}
Swift 5
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let headerView = view as? UITableViewHeaderFooterView else { return }
headerView.backgroundView?.backgroundColor = .red
}
And, if you want different header background (and/or text) colors for each section:
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let headerView = view as? UITableViewHeaderFooterView else { return }
switch section {
case 0:
headerView.backgroundView?.backgroundColor = .red
headerView.textLabel?.textColor = .white
case 1:
headerView.backgroundView?.backgroundColor = .green
headerView.textLabel?.textColor = .white
case 2:
headerView.backgroundView?.backgroundColor = .yellow
headerView.textLabel?.textColor = .black
// etc
default:
return
}
Swift5
Versión updated to iOS 11,12,13,14 with example
change background color and text color:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let tableView = view as? UITableViewHeaderFooterView else { return }
tableView.textLabel?.textColor = UIColor.white
tableView.contentView.backgroundColor = UIColor.black
}
Full example of viewcontroller:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
private let array: [String] = ["ab","bc","cd","de","ef","fg","gh","hi","ij","jk"]
let sectionHeaderTitleArray = ["test1","test2", "test3"]
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 11, *) {}
else {
self.edgesForExtendedLayout = []
}
configTableview()
}
private func configTableview() {
tableView.registerCell(type: SyncCell.self)
tableView.separatorColor = #colorLiteral(red: 0, green: 0.3066673801, blue: 1, alpha: 0.19)
tableView.delegate = self
tableView.dataSource = self
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let tableView = view as? UITableViewHeaderFooterView else { return }
tableView.textLabel?.textColor = UIColor.white
tableView.contentView.backgroundColor = UIColor.black
}
func tableView(_ tableView: UITableView,titleForHeaderInSection section: Int) -> String? {
return sectionHeaderTitleArray[section]
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 130
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("selected cell: \(indexPath)")
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = array[indexPath.row]
let cell = tableView.dequeueReusableCell(type: SyncCell.self, forIndexPath: indexPath)
cell.configCell(text: item)
cell.selectionStyle = .none
return cell
}
}
If you are using titleForHeaderInSection, then the easiest way is to add in viewDidLoad():
self.tableView.backgroundColor = UIColor.clear
For some reason, setting ClearColor for Background in the View section for the TableView in the Interface Builder doesnt always set it to transparent. But adding this one line in the code (for me at least) does.
override viewForHeaderInSection and create UITableViewHeaderFooterView
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var headrview = tableView.dequeueReusableHeaderFooterView(withIdentifier: "aaa")
if headrview == nil {
headrview = UITableViewHeaderFooterView(reuseIdentifier: "aaa")
}
let bview = UIView()
bview.backgroundColor = Theme.current.navigationColor
headrview?.backgroundView = bview
headrview?.textLabel?.textColor = Theme.current.primaryTextColor
return headrview
}
Swift 4 solution.
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView:UIView = UIView()
headerView.backgroundColor = UIColor.lightGray
return headerView
}
If you have a custom header view, you can do it with contentView.backgroundColor.
There is no need to use hacks such as willDisplayHeaderView method or others.
Simply create your own class of UITableViewHeaderFooterView.
Then in func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? return your created custom header view. You should change background color not directly for your header view but for contentView of your header view 🙂
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: NotificationSettingsHeaderView.reuseIdentifier) as! NotificationSettingsHeaderView
headerView.label.text = dataSource.snapshot().sectionIdentifiers[section].title
headerView.contentView.backgroundColor = .red
return headerView
What's even better is to setup background color in init of your header view subclass
This will change it for all the headers in your application :
UITableViewHeaderFooterView.appearance().backgroundColor = theme.subViewBackgroundColor
override or implement the function tableview will display
public func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let headerView = (view as? UITableViewHeaderFooterView)
headerView?.tintColor = .clear
}
We can change the footer color in a section of tableView using the below code snippet.
call the Method heightForFooterInSection
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 5.0
}
call the method viewForFooterInSection
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let viw = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 5))
viw.backgroundColor = .white
return viw
}
Hope this will help you. This is a tested Code.

Resources