渐变颜色随内容视图的高度而变化

时间:2017-02-27 07:03:24

标签: ios swift tableviewcell

我在内容视图中制作了一个自定义单元格我已经设置了渐变效果的背景。下面是我的代码

override func awakeFromNib() {
    super.awakeFromNib()
    view1.backgroundColor = UIColor.whiteColor()
    view1.layer.shadowRadius = 10
    view1.layer.shadowOffset = CGSizeMake(0, 0)
    view1.layer.shadowColor = UIColor.blackColor().CGColor
    view1.clipsToBounds = false
    self.view1.layer.shadowOpacity = 0.3;

    view1.layer.cornerRadius = 5
    view2.layer.cornerRadius = 5

    descriptionLabel.textColor = UIColor.lightGrayColor()
    self.setupGradient()
}

func setupGradient() {
    let gradient: CAGradientLayer = CAGradientLayer()
     gradient.frame = self.view2.bounds
     gradient.colors = [  UIColor(red: 152.0/255.0, green: 116.0/255.0, blue: 189.0/255.0, alpha: 1.0).CGColor, UIColor(red: 105.0/255.0, green: 88.0/255.0, blue: 158.0/255.0, alpha: 1.0).CGColor  ]
     gradient.locations = [0.0, 0.75]
     gradient.cornerRadius = 5
     self.view2.layer.insertSublayer(gradient, atIndex: 0)
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCellWithIdentifier("RewardDetailCell", forIndexPath: indexPath) as! RewardDetailCell
     cell.descriptionLabel.text = labelArray[indexPath.row]
     cell.points.text = dataArray[indexPath.row]
     cell.totalPoints.text = pointsDetail[indexPath.row]
     return cell
}

随着高度的增加,渐变效果也会变得荒谬。 enter image description here

2 个答案:

答案 0 :(得分:2)

只需覆盖l ayoutSubviews 方法,并使渐变图层的边框等于相关视图的边界,以便渐变图层可以与相关视图相同。

答案 1 :(得分:0)

您在“setupGradient()”中编写的代码,从cellForRowAtIndexPath调用该方法,因为在第一次创建单元格时将调用awakeFromNib(),因此渐变图层的矩形仅适用于第一个单元格,因此它是其他细胞的高度不增加。所以从awakeFromNib()中删除self.setupGradient()行。所以你需要实现下面的代码。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("RewardDetailCell", forIndexPath: indexPath) as! RewardDetailCell
    cell.descriptionLabel.text = labelArray[indexPath.row]
    cell.points.text = dataArray[indexPath.row]
    cell.totalPoints.text = pointsDetail[indexPath.row]
    cell.setupGradient()
    return cell
}