3

I have a macOS SwiftUI app with a master-detail split view created with a NavigationView, left column a list and detail view on the right. List content rows are NavigationLinks embedding a custom view with a couple of Text elements.

Is there any way to change the text color on selected rows? I use the pink highlight color on macOS, and (when using light appearance) SwiftUI knows to change the text in some controls to white when they're highlighted (segmented picker, at least.) But I have no idea how to do that in my list rows, where .foregroundColor(Color.primary) keeps the text black regardless of the background color of the row.

This is with Xcode 11.2.1 running on macOS 10.15.2.

2
  • Do you use the selection binding of the List ?. If so it should be easy to compare the cell index with the selection and based on this switch the text foregroundColor. Commented Dec 15, 2019 at 11:39
  • @MarcT. I've tried to, but it doesn't look like it's doing anything — I've tried to give it a Binding to my row item type and I've tried an Int, but the setter is never called. Is there a good explanation of the selection binding anywhere? Commented Dec 16, 2019 at 6:09

1 Answer 1

0

Accessible colors

I found this in an Apple SwiftUI tutorial. It is an extension to Color and returns white or black whichever is more accessible on the background color:

extension Color: Codable {
    var accessibleFontColor: Color {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        UIColor(self).getRed(&red, green: &green, blue: &blue, alpha: nil)
        return isLightColor(red: red, green: green, blue: blue) ? .black : .white
    }

    private func isLightColor(red: CGFloat, green: CGFloat, blue: CGFloat) -> Bool {
        let lightRed = red > 0.65
        let lightGreen = green > 0.65
        let lightBlue = blue > 0.65

        let lightness = [lightRed, lightGreen, lightBlue].reduce(0) { $1 ? $0 + 1 : $0 }
        return lightness >= 2
    }
}

And you can use it like this for ex:

[...]
MyRowView()
    .background(backgroundColor)
    .foregroundColor(backgroundColor.accessibleFontColor)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.