创建一个转换,其移除取决于移除视图时的 @State 值 [英] Create a transition whose removal depends on a @State value when the view is removed

查看:22
本文介绍了创建一个转换,其移除取决于移除视图时的 @State 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个转换,其移除取决于移除视图时的 @State 值.

I would like to create a transition whose removal depends on a @State value when the view is removed.

这是我尝试过的.

如果视图出现时isValid为真,它会使用.move(edge: .trailing)进行移除,即使isValid同时变为假.

If isValid is true when the view appears, it will use .move(edge: .trailing) for removal, even if isValid becomes false in the meantime.

我试图获得的是 .move(edge: .leading) 转换,如果 isValidfalse 当视图被删除,即使如果插入视图时为 true.

What I try to obtain is .move(edge: .leading) transition if isValid is false when the view is removed, even if it was true when the view was inserted.

当我同时切换 showisValid 时出现问题.

The problem appears when I toggle show and isValid at the same time.

struct TextTransitionView: View {
    @State var isValid = false
    @State var show = false

    var body: some View {
        VStack {
            Spacer()

            if show {
                Text("TEXT").transition(slideTransition)
            }

            Spacer()

            Text("Move to \(isValid ? "right" : "left")")

            Button("Toggle isValid") {
                self.isValid.toggle()
            }

            Button("Toggle show") {
                withAnimation { self.show.toggle() }
            }

            Button("Toggle isValid and show") {
                withAnimation {
                    self.isValid.toggle()
                    self.show.toggle()
                }
            }
        }
    }

    var slideTransition: AnyTransition {
        let removal = isValid ? AnyTransition.move(edge: .trailing) : AnyTransition.move(edge: .leading)
        return .asymmetric(insertion: .identity, removal: removal)
    }
}

推荐答案

问题在于 isValid.toggle() 位于 withAnimation 中.从 withAnimation 块中取出这一行解决了这个问题.

The problem was with isValid.toggle() being inside the withAnimation. Getting this line out of the withAnimation block solved the problem.

Button("Toggle isValid and show") {
    self.isValid.toggle()
    withAnimation {
        self.show.toggle()
    }
}

这篇关于创建一个转换,其移除取决于移除视图时的 @State 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆