I have a problem with a view inside a tableViewCell. So I have a tableViewCell, inside of that I have a UIView I called "containerView". Now I want the background of the containerView to be a gradient from light gray to dark gray. In the following code you can see how I set the layer and everything, but for some reason the "backgroundColor" with the gradient is a little off to the right and downwards. Hope you can help me fix this problem, it's the first time I am working with gradient so please be patient :D
import UIKit
class customCell: UITableViewCell {
@IBOutlet var containerView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let layerView = UIView()
layerView.layer.frame = containerView.layer.frame
let layer = CAGradientLayer()
layer.frame = containerView.layer.frame
layer.colors = [UIColor.lightGrayColor().CGColor, UIColor.darkGrayColor().CGColor]
layerView.layer.addSublayer(layer)
containerView.addSubview(layerView)
containerView.sendSubviewToBack(layerView)
}
}
This is how I have assigned gradient color as background of my custom cell
let startingColorOfGradient = UIColor(colorLiteralRed: 217/255, green: 90/255, blue: 57/255, alpha: 1.0).CGColor
let endingColorOFGradient = UIColor(colorLiteralRed: 227/255, green: 214/255, blue: 42/255, alpha: 1.0).CGColor
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = bounds
gradient.startPoint = CGPoint(x: 0.5, y: 0.0)
gradient.endPoint = CGPoint(x: 0.5, y:1.0)
gradient.colors = [startingColorOfGradient , endingColorOFGradient]
// backGroundView is a View I have placed on my cell as container
self.backGroundView.layer.insertSublayer(gradient, atIndex: 0)
The following code will assign gradient color to view background.
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:38/255.0 green:154/255.0 blue:255.0/255.0 alpha:1] CGColor], (id)[[UIColor colorWithRed:30/255.0 green:88/255.0 blue:151/255.0 alpha:1] CGColor], nil];
[self.view.layer insertSublayer:gradient atIndex:0];
This how i add gradient layer to canvasView(UIView) background. And background of UIView should be clear.
func addGradient(color:UIColor){
let gradient:CAGradientLayer = CAGradientLayer()
gradient.frame.size = self.canvasView.frame.size
gradient.colors = [color.cgColor,color.withAlphaComponent(0).cgColor] //Or any colors
self.canvasView.layer.addSublayer(gradient)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.