1

I was able to add a gradient my UITableView, but I have the issue of when I have to scroll through my cells, the gradient background scrolls along also. I want the background to stay consistent as I scroll up or down. How can I achieve this? Do I have to create a custom UITableView in order to do this?

The pictures below show what it currently looks like.

Here is my code for adding the gradient to the UITableView:

func addGradientToBackground(){
    var gradient : CAGradientLayer = CAGradientLayer()
    gradient.frame = self.tableView.bounds
    gradient.colors = [UIColor.blueColor().CGColor, UIColor.redColor().CGColor]
    self.tableView.layer.insertSublayer(gradient, atIndex: 0)
}

Messing around will setting the gradient doesn't work either, like setting:

self.view.layer.insertSublayer(gradient, atIndex: 0)

or changing the bounds:

gradient.frame = self.tableView.frame

Also, in cellForRowAtIndexPath I set the UITableViewCells background color to clear:

cell.backgroundColor = UIColor.clearColor()

I can't add images, but here is the link if you wish to see them: https://i.stack.imgur.com/9C51p.png

jacks205
  • 545
  • 8
  • 19

2 Answers2

4

The gradient needs to be behind the table view if you don't want it to scroll. If you're using a UITableViewController, the only thing behind is the window, so you could give it the gradient, and make the cells and the table view have a clear background color. If you're using a UIViewController with a table view as a subview, then you could give the controller's main view a gradient background color.

rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • Thanks for the help! I just moved my `addGradientToBackground()` to `AppDelegate.swift` and changed `self.view` to `self.window` and it did the trick. – jacks205 Mar 24 '15 at 20:19
0

Have you thought to add a background image as follows?

var imageView = UIImageView(frame: CGRectMake(10, 10, cell.frame.width - 10, cell.frame.height - 10))
let image = UIImage(named: ImageNames[indexPath.row])
imageView.image = image
cell.backgroundView = UIView()
cell.backgroundView.addSubview(imageView)
casillas
  • 16,351
  • 19
  • 115
  • 215
  • So I just edited my post, but I am not applying any gradient to the cells. I actually just set their backgrounds to clear `cell.backgroundColor = UIColor.clearColor()`. I wish to apply the gradient just purely to the UITableView background and do nothing to each individual UITableViewCell regarding the gradient. – jacks205 Mar 24 '15 at 20:03