【问题标题】:Iterate over available classes in a Swift extension?迭代 Swift 扩展中的可用类?
【发布时间】:2018-05-11 16:24:04
【问题描述】:

我以前从未尝试过的事情,但我有一个如下所示的扩展(为简洁起见),我希望能够在代码中绘制出每种可用的颜色。我以前从未尝试过,并且无法将正确的搜索词组合在一起甚至接近。想法,指针?

我想以某种方式让let availableColors: [UIColor] = magicalFunctionHere(pointing 扩展)....

我想我必须创建自己的函数并手动插入扩展中的 UIColors。不过,我更愿意自动执行此操作。

extension UIColor {
    class func firstColor ( alpha: CGFloat = 1.0 ) -> UIColor {
        return  UIColor.init ( red: 139.0/255.0, green: 322.0/255.0, blue: 405.0/255.0, alpha: alpha )
    }

    class func secondColor ( alpha: CGFloat = 1.0 ) -> UIColor {
        return  UIColor.init ( red: 225.0/255.0, green: 139.0/255.0, blue: 127.0/255.0, alpha: alpha )
    }
}

【问题讨论】:

  • 这可能会有所帮助,我确实已经看到了,但它是基于 instance 的,这不是我想要的。例如,我寻求能够查询可用颜色以从中创建一个数组,然后提供一个选择器。我会重新检查你的链接,以防我错过了要点;)..但是,内部代码显然存在,因为它显示在自动完成中。
  • 您可以使用 Obj-C 运行时或使用 Mirror 的反射,但一般而言,这将违反 OOP。
  • 顺便说一句,您应该更喜欢使用let 常量作为颜色,然后使用UIColor.withAlphaComponent,而不是使用带有alpha 参数的函数。
  • 顺便说一句,您的颜色组件毫无意义。 322.0 / 255.0 无效,因为 1.0 是组件的最大值。
  • 感谢 sultham.. 很好地了解了这些数字,我只是从原始 git 中编辑了一些内容,而不仅仅是复制别人的工作。这是来自 GitHub 的 git,它在允许最终用户选择颜色方面可能非常有用,但产品的庞大规模使我无法手动进行。我只是在做一个穷人的混淆;)(阿尔法问题是 git 的一部分,而不是我的设计)。对于那些感兴趣的人,原件位于github.com/NorthernRealities/Rainbow。我正在评估 EVReflection 以完成我的目标。

标签: ios swift class swift4 extension-methods


【解决方案1】:

这是使用 Obj-C 运行时方法的代码(注意 @objc 前缀,它们是使运行时“看到”您的方法所必需的):

import Foundation
import XCPlayground
import UIKit

extension UIColor {
    @objc class func fancyColorFirst ( alpha: CGFloat = 1.0 ) -> UIColor {
        return UIColor.red.withAlphaComponent(alpha)
    }

    @objc class func fancyColorSecond ( alpha: CGFloat = 1.0 ) -> UIColor {
        return UIColor.blue.withAlphaComponent(alpha)
    }
}

func methods(in c: AnyClass, where condition: (String) -> Bool ) -> [String] {
    var count: UInt32 = 0
    guard let foundMethods = class_copyMethodList(object_getClass(c), &count) else { return [] }

    let totalMethods = Int(count)
    var matches = [String]()

    for index in 0..<totalMethods {
        let method: Method = foundMethods[index]
        let selector: Selector = method_getName(method)
        let methodName = String(_sel:selector)
        if condition(methodName) {
            matches.append(methodName)
        }
    }
    return matches
}

print(methods(in: UIColor.self, where: { $0.hasPrefix("fancyColor")}))

【讨论】:

  • 但更好的办法是使用协议来声明某种“契约”,然后检查您的类/结构是否支持它。
  • 谢谢@Sergiy!我将测试此代码并返回结果并相应地检查您的回复,干杯!画了..
猜你喜欢
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
  • 1970-01-01
  • 2019-03-05
  • 1970-01-01
相关资源
最近更新 更多