The function that Apple has already put in iOS that is in Settings -> General -> Accessibility -> Invert colors, can I somehow use that in my program so for say when the user touches the screen the colors invert?
4 Answers
I don't know of a way to do this automatically, but you could invert colors yourself using an extension on UIColor and accessing the subviews?
extension UIColor { var inverted: UIColor { var r: CGFloat = 0.0, g: CGFloat = 0.0, b: CGFloat = 0.0, a: CGFloat = 0.0 self.getRed(&r, green: &g, blue: &b, alpha: &a) return UIColor(red: (1 - r), green: (1 - g), blue: (1 - b), alpha: a) // Assuming you want the same alpha value. } } And then if you want to update specific properties of the views you could do something like this:
view.subviews.map { $0.backgroundColor = $0.backgroundColor.invertedColor } // And so on to change things like the tint color, text color, etc. Sorry, I don't know a way to do this directly but till then this is better than nothing I guess.
1 Comment
UIColor.red.getRed(&r, green: &g, blue: &b, alpha: &a) into self.getRed(&r, green: &g, blue: &b, alpha: &a)Now this can be done with a buid-in method from SwiftUI; colorInvert().
The colorInvert() modifier inverts all of the colors in a view so that each color displays as its complementary color. For example, blue converts to yellow, and white converts to black.
See: https://developer.apple.com/documentation/swiftui/view/colorinvert()
Comments
works in SwiftUI also:
extension NSColor { var inverted: NSColor { var r: CGFloat = 0.0, g: CGFloat = 0.0, b: CGFloat = 0.0, a: CGFloat = 0.0 self.getRed(&r, green: &g, blue: &b, alpha: &a) return NSColor(red: (1 - r), green: (1 - g), blue: (1 - b), alpha: a) } } extension Color { var inverted: Color { Color(nsColor: self.nsColor.inverted) } } @available(macOS 12.0, *) public extension Color { var nsColor: NSColor { NSColor(self) } var cgColor: CGColor { nsColor.cgColor } }