简体   繁体   English

SwiftUI:如何仅将修饰符应用于特定元素?

[英]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.所以我有这个非常简化的代码,我基本上有一个带有自定义修饰符的 HStack。

My question is, how can i keep the modifier on the HStack, but dont let the modifier apply to the button inside the HStack?我的问题是,我怎样才能将修饰符保留在 HStack 上,但不要让修饰符应用于 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在这种情况下,我可以直接将修饰符应用于文本字段,但正如我所提到的,这是我的代码的一个非常简化的版本,所以我们假设修饰符必须在 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!在您的情况下,ViewModifier 认为内容是整个 HStack,这实际上是您最近告诉 SwiftUI 将我的 HStack 作为内容并作为内容使用 TFModifier 修改它! in this case there is no way to tell SwiftUI put Button out of calculation!在这种情况下,没有办法告诉 SwiftUI 把 Button 排除在计算之外! It is 100% impossible!这是100%不可能的! SwiftUI does not care about your naming like TFModifier , it just care about incoming content! SwiftUI 不像TFModifier那样关心你的命名,它只关心传入的内容! and like I said you are feeding the entire HStack as content!就像我说的那样,您将整个 HStack 作为内容提供! It is better think where you want acutely apply this modification!最好想想你想在哪里敏锐地应用这个修改!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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