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

前端 未结 6 1639
情书的邮戳
情书的邮戳 2021-01-31 02:46

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.

6条回答
  •  广开言路
    2021-01-31 03:30

    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
    }
    

提交回复
热议问题