简体   繁体   中英

UIColor swift extension w/ class access from Objective-C

How can I access my darkGray color from objective-c please?

@objc
extension UIColor
{
    @objc
    public class Scheme1: NSObject {
        static var darkGray: UIColor! {
            return UIColor(red: 16.0/255.0, green: 16.0/255.0, blue: 19.0/255.0, alpha: 1.0)
        }
    }
}

Assuming you're using Swift 4's @objc inference, darkGray must be declared @objc :

@objc
extension UIColor
{
    @objc
    public class Scheme1: NSObject {
        @objc static var darkGray: UIColor! {
            return UIColor(red: 16.0/255.0, green: 16.0/255.0, blue: 19.0/255.0, alpha: 1.0)
        }
    }
}

You can access darkGray from Objective-C using Scheme1.darkGray . Objective-C does not support nested classes, so Scheme1 is exported at the top level.


If you really want to access Scheme1 in a namespaced manner even from Objective-C, you can make darkGray an instance property and store an instance of Scheme1 in your extension:

@objc
extension UIColor
{
    @objc
    public class Scheme1: NSObject {
        @objc var darkGray: UIColor! {
            return UIColor(red: 16.0/255.0, green: 16.0/255.0, blue: 19.0/255.0, alpha: 1.0)
        }
    }

    @objc public static var scheme1 = Scheme1()
}

You can access darkGray using UIColor.scheme1.darkGray .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM