Hi, I have the following Swift code which works as...
# kotlin-native
t
Hi, I have the following Swift code which works as expected:
Copy code
import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let layer = createGradient()
        layer.frame = self.view.bounds
        self.view.layer.addSublayer(layer)
    }

    func createGradient() -> CAGradientLayer {
        let layer = CAGradientLayer()
        layer.type = kCAGradientLayerAxial
        layer.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
        return layer
    }
}
I would like to convert the createGradient function to Kotlin. This is what I have tried:
Copy code
import platform.QuartzCore.CAGradientLayer
import platform.QuartzCore.kCAGradientLayerAxial
import platform.UIKit.UIColor
fun createGradient(): CAGradientLayer {
    val layer = CAGradientLayer()
    layer.type = kCAGradientLayerAxial
    layer.colors = listOf(UIColor.redColor.CGColor, UIColor.blueColor.CGColor)
    return layer
}
When using this function the layer just doesn’t appear on the screen. As if it is completely transparent. I think something could be going wrong with the colors. Could anyone here help me out?
đź‘€ 1
s
You have type mismatch here.
CGColorRef
is CoreFoundation type. Current interop implementation in Kotlin doesn’t handle CoreFoundation types as reference types and doesn’t automatically bridge them to Objective-C references, so you have to bridge explicitly here, properly handling memory management. Consider taking a look at https://developer.apple.com/documentation/foundation/1587932-cfbridgingrelease
t
@svyatoslav.scherbina thanks for the explanation. However, this code still has some issues. It’s getting EXC_BAD_ACCESS after calling it multiple times. Is the code below correct or am I still doing it wrong?
Copy code
fun createGradient(): CAGradientLayer {
    val layer = CAGradientLayer()
    layer.type = kCAGradientLayerAxial
    val colors = listOf(UIColor.redColor.CGColor, UIColor.blueColor.CGColor)
    layer.colors = colors.map { CFBridgingRelease(it) }
    return layer
}
s
I’m not sure your code handles memory management properly. You may also need
CFRetain
here.