Search code examples
swiftuitipkit

SwiftUI Customize Tip that is popoverTip


enter image description here

Hi, i'm using tipKit - popoverTip, from the box it uses some kind of Color.secondary for backGround. But i need customize the background color of the tip in popoverTip.

Is it possible to customize tip, that is popoverTip type?

I found, that i could change foreground color of each element, but is doesn't work to change the back ground of the tip.

TipView looks different, and is not appropriate here


Solution

  • Use TipViewStyle to customize tips.

    enter image description here

    struct CustomTipViewStyle: TipViewStyle {
        func makeBody(configuration: TipViewStyle.Configuration) -> some View {
            VStack {
                HStack(alignment: .top) {
                    configuration.image?
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 40.0, height: 40.0)
                        .foregroundStyle(.gray)
    
    
                    VStack(alignment: .leading, spacing: 8.0) {
                        configuration.title?
                            .font(.headline)
                        configuration.message?
                            .font(.subheadline)
    
                        ForEach(configuration.actions) { action in
                            Button(action: action.handler) {
                                action.label().foregroundStyle(.blue)
                            }
                        }
                    }
                    
                    Button(action: { configuration.tip.invalidate(reason: .tipClosed) }) {
                        Image(systemName: "xmark").scaledToFit()
                            .foregroundStyle(.white)
                    }
                }
            }
            .padding()
            .background(.indigo)
        }
    }
    
    struct PopoverTip: Tip {
        var title: Text {
            Text("Write what you want")
                .foregroundStyle(.white)
        }
        var message: Text? {
            Text("And our AI will create an unique image for you")
                .foregroundStyle(.white)
        }
        var image: Image? {
            Image(systemName: "wand.and.stars")
        }
    }
    
    struct TipKitView: View {
        let popoverTip = PopoverTip()
        @State private var text: String = ""
    
        var body: some View {
            VStack {
                TextField("Enter your name", text: $text)
                    .textFieldStyle(.roundedBorder)
                    .popoverTip(popoverTip)
                    .onTapGesture {
                        popoverTip.invalidate(reason: .actionPerformed)
                    }
                    .tipViewStyle(CustomTipViewStyle())
                Spacer()
            }
            .padding()
        }
    }