Warm tip: This article is reproduced from stackoverflow.com, please click
image swift swiftui sf-symbols

SwiftUI changing the color of clear part inside of SF Symbol

发布于 2020-04-08 09:31:04

I am trying to change the color of clear(transparent) part inside of a SF Symbol called delete.left.fill. So far I've tried is as follows

Button(action: { return }, label: {
                        Image(systemName: "delete.left.fill")
                            .background(Color.black)
                            //.accentColor(.black)
                            .font(.system(size: self.fontSize*0.75))
                    })
                        .frame(width: self.width, height: self.width)
                        .foregroundColor(.lightGray)
                        //.background(Color.black)

When I run the code as above, the result is like

symbol.

At first, the xinside of the symbol was the same color as background. I want it to make black.

  1. I tried to set the backgroundColor of the Button and it made whole Button black.
  2. I tried to set accentColor of the Image to black. Nothing changed.
  3. I tried to set backgroundColor of the Image to black. The result can be seen in the image.

The question is, is there a way to make just that x, inside the symbol, black programmatically?

Questioner
Faruk
Viewed
142
nine stones 2020-02-02 01:28

You could mask the background and apply a custom style:

struct MyButtonStyle: ButtonStyle {
  public func makeBody(configuration: MyButtonStyle.Configuration) -> some View {
    configuration.label
      .compositingGroup()
      .opacity(configuration.isPressed ? 0.5 : 1.0)
  }
}

Button(action: {}) {
  Image(systemName: "delete.left.fill")
    .foregroundColor(.green)
    .background(
      Color.black.mask(Circle())
    )
}.buttonStyle(MyButtonStyle())

The circle may not fit to any usage, but for this image it works okay:

enter image description here