Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 743
Vikas Seth Avatar asked Jun 06 '15 06:06

Vikas Seth


People also ask

How do I change the color of a table in Xcode?

Change the background color of Table View Cell. In the Document Outliner, select the Table View's cell. Click on the Attributes inspector. In the View section set the background color to red: 108, green: 255, blue: 146, alpha 1.

How do I change the color of a view in Swift?

Find the view or view controller you want to change the background color of. Open it up in the interface builder and open the Attributes Inspector. Find the background color field and set it to the color you want.


3 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
}
like image 117
Homam Avatar answered Oct 19 '22 18:10

Homam


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
}
like image 37
Lucas Farah Avatar answered Oct 19 '22 18:10

Lucas Farah


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

like image 7
user6082493 Avatar answered Oct 19 '22 18:10

user6082493