Home>

Is there an easy way to get thesystemFillColorpart of the code below as a string?

class customLabel: UILabel {
    override func awakeFromNib () {
        super.awakeFromNib ()
        if let backgroundColor = backgroundColor {
            print ("backgroundColor: \ (backgroundColor)")
            // =>backgroundColor:<UIDynamicSystemColor: 0x28087bfa0;name = systemFillColor>
        }
    }
}

Primitive? Please tell me if you know because there is only a way.

extension UIColor {
    var name: String? {
        switch self {
        case UIColor.systemFill: return "systemFillColor"
        ...
        ...
        default: return nil
        }
    }
}
  • Answer # 1

    I didn't understand regular expressions at all, but it was appropriate.

    let color = UIColor.systemFill
    let colorStr = String (describing: color)
    let colorNSStr = String (describing: color) as NSString
    let pattern = "= (. *?)>"
    let range = NSRange (location: 0, length: colorNSStr.length)
    let str: String
    if let regex = try? NSRegularExpression (pattern: pattern),
       let match = regex.firstMatch (in: colorStr, options: [], range: range) {
        str = colorNSStr.substring (with: match.range (at: 1))
    } else {
        str = ""
    }
    print (str) // =>systemFillColor