XYZ
XYZ

Reputation: 27397

How to apply animation for one specific modifier change only?

How to only apply .animation to .offset while keeping other modifier change not affected by it. Adding .animation after offset would also animate the font size changing.

enter image description here

// Main view
var body: some View {
    GeometryReader { geo in
        VStack {
            DynamicText()
        }
        .frame(height: geo.size.height)
        .offset(y: self.viewModel.offset ? 5.0 : 0)
        .animation(.default)
    }
}

// DynamicText view
var body: some View {
    return GeometryReader { geo in
        VStack {
            Text("Foo")
                .font(
                    .system(size: geo.size.height * 0.95, weight: .regular, design: .monospaced))
                .minimumScaleFactor(0.05)
                .lineLimit(1)
                .foregroundColor(Color("primary"))
        }
        .frame(height: geo.size.height)
    }
}

Also tried putting .animation(nil) for modifiers above have no intention for animating, however, it also stops the offset from animating. Because of the ZStack contains different conditional rendered DynamicText the animation modifier also applies the fade-in-out transition between the content changes which is something I want to avoid.

// Main view
var body: some View {
    GeometryReader { geo in
        VStack {
            DynamicText()
        }
        .animation(nil)
        .frame(height: geo.size.height)
        .offset(y: self.viewModel.offset ? 5.0 : 0)
        .animation(.default)
    }
}

Upvotes: 4

Views: 887

Answers (1)

Asperi
Asperi

Reputation: 257799

The provided snapshot is not testable, so just a thought - try to limit animation to offset value explicitly, like

var body: some View {
    GeometryReader { geo in
        VStack {
            DynamicText()
        }
        .frame(height: geo.size.height)
        .offset(y: self.viewModel.offset ? 5.0 : 0)
        .animation(.default, value: self.viewModel.offset)     // << here !!
    }
}

Upvotes: 8

Related Questions