0

I have UITableView with 2 sections(each section has n number of rows). I have a requirement to add gradient color to first section only. Is there any way to add gradient color on a paticular section of UITableView?

Ashish Verma
  • 1,776
  • 1
  • 16
  • 27
  • have you tried this ? http://stackoverflow.com/questions/8413436/change-uitable-section-backgroundcolor-without-loosing-section-title – Umair Afzal Jun 30 '16 at 07:31
  • My requirement is not to change the header/footer view of a section. I have table view cells with clear color background and I want to show gradient color on a particular section of a table view – Ashish Verma Jun 30 '16 at 07:36

2 Answers2

0

You can just compare which section that you would like to show gradient color. Example:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let view: UIView = UIView(frame: CGRectMake(0.0, 0.0, 320.0, 50.0))

    if section == 0 {  // for your gradient section. it can be any section that you want

       let gradient: CAGradientLayer = CAGradientLayer()
       gradient.frame = view.bounds
       gradient.colors = [UIColor.whiteColor().CGColor, UIColor.blackColor().CGColor]
       view.layer.insertSublayer(gradient, atIndex: 0)

    } else {
       view.backgroundColor = UIColor.lightGrayColor()

    }
    return view
}
Syed M
  • 81
  • 5
0

Apple only allows to change the header or footer, not the view you want. Instead you can set gradient to each cell in Section 0

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let Identifier = "RWCellIdentifier"
    var cell = tableView.dequeueReusableCellWithIdentifier(Identifier)
    if (cell == nil) {
        cell = UITableViewCell(style: .Default, reuseIdentifier: Identifier)
    }
    cell?.textLabel?.text = "text test"

//gradient color
    if indexPath.section == 0 {
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame = CGRectMake(0, 0, self.view.frame.width, cell!.frame.height)
        gradient.colors = [UIColor.redColor().CGColor, UIColor.yellowColor().CGColor]
        cell!.layer.insertSublayer(gradient, atIndex: 0)
    }
    return cell!
}

here's how it looks

ronan
  • 1,611
  • 13
  • 20