1

I want to change my UITableViewController background color as gradient color.

My code is as below:

override func viewDidLoad() {
    super.viewDidLoad()

    let gradient = CAGradientLayer()
    let gradientLocations = [0.0,1.0]

    gradient.frame = view.bounds;
    gradient.colors = [primaryColor, secondaryColor]
    gradient.locations = gradientLocations as [NSNumber]?

    let backgroundView = UIView(frame: view.bounds)
    backgroundView.layer.insertSublayer(gradient, at: 0)
    tableView.backgroundView = backgroundView

    tableView.separatorStyle = UITableViewCellSeparatorStyle.none
    tableView.backgroundColor = UIColor.clear

}

And it becomes black color.

I found this very similar question but it couldn't solve my problem. Set gradient behind UITableView

enter image description here

Please help! Thanks in advance.

Community
  • 1
  • 1
raimtoon
  • 725
  • 1
  • 11
  • 27
  • My google search... "swift 3 gradient background".. top result.. http://stackoverflow.com/questions/24380535/how-to-apply-gradient-to-background-view-of-ios-swift-app. Although that's not specifically for a table view, it should solve one of your problems... then all of them. –  Mar 25 '17 at 20:42

1 Answers1

2

I created a new project with a table view controller that contains exactly your code. All I had to do was make the cells transparent, too, just like the post you linked to said. It worked, so this made me curious. You did not show what primaryColor and secondaryColor are.

Note that you need to use CGColors in gradient.colors. I just tried using UIColors and the screen was just as black. Try using

gradient.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]

or rather (if they are indeed of type UIColor)

gradient.colors = [primaryColor.cgColor, secondaryColor.cgColor]
thm
  • 1,217
  • 10
  • 12