本文介绍了Xcode 8 Beta 4 CGColor.components不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然下面的代码以前可以工作,但是它已停止在Xcode 8 Beta 4中工作,原因可能是components返回是一个非常不迅速的C数组浮点数,因此已被删除.错误是秃头的-'组件'不可用"-我找不到替换它的东西,如果有的话.有谁知道如何产生相同的功能?

Whilst the code below worked previously, it has stopped working in Xcode 8 Beta 4, presumably because the components return was a very un-Swift-y C-array of floats, and has been removed. The error is bald - "'components' is unavailable" - and I can't find what has replaced it, if anything. Does anyone know how to produce the same functionality?

public var cgColour: CGColor {
    get {
        return CGColor(red: self.colourRed, green: self.colourGreen, blue: self.colourBlue, alpha: self.colourAlpha)
    }
    set {
        let comps = newValue.components // No longer available
        self.colourRed = (comps?[0])!
        self.colourGreen = (comps?[1])!
        self.colourBlue = (comps?[2])!
        self.colourAlpha = (comps?[3])!
    }
}

更新@Hamish的答案有效,但我的初衷是不使用UIColor或NSColor以便我的代码在iOS&苹果系统.我最后要做的就是这个...

Update@Hamish's answer works, but my original intent was not to use UIColor nor NSColor so that my code works in both iOS & MacOS. What I've ended up doing is this...

#if os(iOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif

extension CGColor {
    var components: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        #if os(iOS)
            UIColor(cgColor: self).getRed(&r, green: &g, blue: &b, alpha: &a)
        #elseif os(OSX)
            NSColor(cgColor: self)?.getRed(&r, green: &g, blue: &b, alpha: &a)
        #endif
        return (r, g, b, a)
    }
}
// Playground code to test...
#if os(iOS)
let rgba = UIColor.brown.cgColor.components //(0.6, 0.4, 0.2, 1.0)
#elseif os(OSX)
let rgba = NSColor.brown.cgColor.components //(0.6, 0.4, 0.2, 1.0)
#endif

...这是这样的大错-有人能得到更好的答案吗?

... this is such a kludge - has anyone got a better answer?

推荐答案

@Hamish的答案有效,但我的初衷是使用UIColorNSColor以便我的代码在iOS和苹果系统. @LeoDabus建议使用SKColor,但这只是NSColorUIColor的类型别名,无论如何都没有直接来自CGColor的初始值,但是,Leo的建议促使我使用 CIColor 代替:

@Hamish's answer works, but my original intent was not to use UIColor or NSColor so that my code works in both iOS & MacOS. @LeoDabus suggested using SKColor, but that's just a type alias to either NSColor or UIColor, and doesn't have a direct init from CGColor anyway, however, Leo's suggestion prompted me to refine my kludge using CIColor instead:

import CoreImage

extension CGColor {
    var components: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
        let ciColor = CIColor(cgColor: self)
        return (ciColor.red, ciColor.green, ciColor.blue, ciColor.alpha)
    }
}

这篇关于Xcode 8 Beta 4 CGColor.components不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 10:15