简体   繁体   English

如何在不重新绘制视图的情况下更新 SwiftUI 中的修改器

[英]How can I update modifier in SwiftUI without re drawing views

I want update my modifier in this way that the orignal content does not get redrawen or re appear for that goal I am using this code:我想以这种方式更新我的修改器,以便原始内容不会被重新绘制或重新出现我正在使用此代码的目标:

struct BigModified: ViewModifier {
    
    func body(content: Content) -> some View {
        return content
            .font(Font.title.bold())
        
    }
    
}

struct ContentView: View {
    
    @State private var start: Bool = false
    var body: some View {
        Text("Hello, world!")
            .modifier(start ? BigModified() : EmptyModifier())
            .onTapGesture { start.toggle() }
    }
}

The error is:错误是:

Result values in '? '? 中的结果值:' expression have mismatching types 'BigModified' and 'EmptyModifier' :' 表达式具有不匹配的类型 'BigModified' 和 'EmptyModifier'

I know that I can use switch or if, but again those make view get appear again.我知道我可以使用 switch 或 if,但是那些使视图再次出现。 Is there a way around to update modifier with a State wrapper like in question, also I should add and tell it is obvious that I can use a parameter inside a ViewModifier for that, But that is not my question, my question is about .modifier(T) itself, more looking some thing like .modifier(T, V, U, ...) be possible to use or build, which takes more than just one viewModifier.有没有一种方法可以使用 State 包装器更新修改器,就像有问题的那样,我还应该添加并告诉我很明显我可以在 ViewModifier 中使用一个参数,但这不是我的问题,我的问题是关于.modifier(T)本身,更像是.modifier(T, V, U, ...)之类的东西可以使用或构建,它需要的不仅仅是一个 viewModifier。

You can declare a view modifier in another way, as a func of View , so you can act on your view based on a boolean parameter.您可以以另一种方式声明视图修饰符,作为Viewfunc ,这样您就可以根据 boolean 参数对视图进行操作。

This is how it works:它是这样工作的:

Modifier:修改器:

extension View {
    
    @ViewBuilder
    func modifier(big: Bool) -> some View {
        if big {
            self
                .font(Font.title.bold())
        } else {
            self
        }
    }
}

How to use it:如何使用它:

var body: some View {
        Text("Hello, world!")
            .modifier(big: start)
            .onTapGesture { start.toggle() }
    }

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

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