简体   繁体   中英

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'

I know that I can use switch or if, but again those make view get appear again. 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.

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.

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() }
    }

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