Zhou Hao Zhou Hao - 1 month ago 22
iOS Question

Issue when I'm trying to draw gradient in swift

I got an error when I was trying to draw gradient in Swift code:


GradientView.swift:31:40: Could not find an overload for '__conversion' that accepts the supplied arguments


Here is my code:

let context: CGContextRef = UIGraphicsGetCurrentContext()
let locations: CGFloat[] = [ 0.0, 0.25, 0.5, 0.75 ]
let colors = [UIColor.redColor().CGColor, UIColor.greenColor().CGColor,UIColor.blueColor().CGColor, UIColor.yellowColor().CGColor]
let colorspace: CGColorSpaceRef = CGColorSpaceCreateDeviceRGB()
let gradient: CGGradientRef = CGGradientCreateWithColors(colorspace, colors, locations)
//CGGradientCreateWithColors(colorspace,colors,locations)
let startPoint: CGPoint = CGPointMake(0, 0)
let endPoint: CGPoint = CGPointMake(500,500)
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);


The problem is the CGGradientCreateWithColors takes CFArray not a normal Swift Array. I have no idea how to convert CFArray to Array and can't find anything in Apple's document. Any idea? Thanks

Answer

You can annotate constant with explicit type CFArray:

let colors: CFArray = [UIColor.redColor().CGColor, ...