How to apply animation for one specific modifier change only?

南笙酒味 提交于 2021-01-27 22:25:43

问题


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.

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

回答1:


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 !!
    }
}


来源:https://stackoverflow.com/questions/63770120/how-to-apply-animation-for-one-specific-modifier-change-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!