Home » Swift » iOS Swift – How to change background color of Table View?

iOS Swift – How to change background color of Table View?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have a simple table view, I can change the colors of cells, but when trying to change the color of Table View (Background part) it is not working… I tried it via Storyboard… Can someone please help

Answers:

First set the background color of the tableView in viewDidLoad like below:

override func viewDidLoad() {
    super.viewDidLoad()   
    self.tableView.backgroundColor = UIColor.lightGrayColor()
}

Now add this method:

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.clearColor()
}

In Swift 3, use below methods instead of above one:

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.backgroundColor = UIColor.lightGray
}

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cell.backgroundColor = UIColor.clear
}

Questions:
Answers:
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.contentView.backgroundColor = UIColor.yellowColor()
}

Swift 3

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cell.contentView.backgroundColor = UIColor.yellow
}

Questions:
Answers:

If you want to achieve that via storyboard then select “Content View” of “table view cell” in your tableView then in attribute Inspector go to View and change its color like so:

Xcode

Questions:
Answers:

use this code for change tableView color

override func viewDidLoad() {
        super.viewDidLoad()

       // define tableview background color
        self.tableView.backgroundColor = UIColor.clearColor()
}

for change tableView cell color

cell.backgroundColor = UIColor.clearColor()