【问题标题】:Swift - using #define in Swift [duplicate]Swift - 在 Swift 中使用#define [重复]
【发布时间】:2014-08-22 17:44:57
【问题描述】:

我有一个Common.h,定义如下:

// Get UIColor from Hex value
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
#define CellTextColor UIColorFromRGB((uint32_t) 0x217EB5)

我希望能够在 Swift 中使用 CellTextColor 进行着色。但它不允许我运行宏。只有当我有 #define value @"string" 时,它才能在 Swift 中运行。

我还有什么需要做的吗?

我阅读了以下链接:

How to use Objective-C code with #define macros in Swift

https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html

【问题讨论】:

    标签: iphone swift


    【解决方案1】:

    具体的答案大概是UIColor上的一个扩展:

    extension UIColor {
    
        class func fromRGB(rgb:UInt32) -> UIColor {
            return UIColor(
                red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
                green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
                blue: CGFloat(rgb & 0x0000FF) / 255.0,
                alpha: CGFloat(1.0)
            )
        }
    
        class var cellTextColor: UIColor {
            return UIColor.fromRGB(0x217eb5)
        }
    
    }
    

    允许您使用:

    let color = UIColor.cellTextColor
    

    更通用的答案是,这一切都将非常依赖于宏是什么以及它最终是如何被使用的。

    【讨论】:

      猜你喜欢
      • 2014-08-11
      • 2016-10-17
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 2018-12-12
      • 1970-01-01
      相关资源
      最近更新 更多