简体   繁体   中英

SwiftUI: How to apply modifiers only to specific elements?

So i have this very simplified code, where I basically have an HStack with a custom modifier.

My question is, how can i keep the modifier on the HStack, but dont let the modifier apply to the button inside the HStack?

In this case i could just apply the modifier directly to the textfield, but as i mentioned, this is a very simplified version of my code, so let's just assume the modifier has to be on the HStack

This is the code

HStack{
    TextField("Enter a Froot", text: self.$searchTxt)
     
    Button(action: {print("Is cancelled")}){
        Text("Cancel")
    }                
}.modifier(TFModifier())

This is the modifier

struct TFModifier : ViewModifier {
    func body(content: Content) -> some View {
        content.padding()
            .background(Color("TesterColor"))
            .overlay(
                RoundedRectangle(cornerRadius: 20)
                    .stroke(Color.black.opacity(0.01), lineWidth: 4)
                    .shadow(color:  Color("TesterColor3"), radius: 6, x: 5, y: 5)
                    .clipShape(RoundedRectangle(cornerRadius: 20))
            )
    }
}

In your case ViewModifier, thinks the content is entire HStack which is actually you are latterly telling to SwiftUI take my HStack as Content and as content modify it with TFModifier! in this case there is no way to tell SwiftUI put Button out of calculation! It is 100% impossible! SwiftUI does not care about your naming like TFModifier , it just care about incoming content! and like I said you are feeding the entire HStack as content! It is better think where you want acutely apply this modification!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM