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

Gradient color changes with the height of the content view

我在其内容视图中创建了一个自定义单元格我已将其背景设置为渐变 effect.Below 是我的代码

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
}

随着高度的增加,渐变效果也发生了荒谬的变化。

您在 "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
}

只需要重写layoutSubviews方法,让渐变层的frame等于相关视图的bound,这样你的渐变层就可以和相关视图有相同的边框了。