不透明度转换在SwiftUI中不起作用,如何使它起作用?

时间:2019-12-11 04:43:19

标签: swift animation swiftui

使用.transition(.opacity)时视图不会淡入和淡出。 (但是.transition(.slide)会设置动画)

如何在不使用withAnimation{}的情况下变得不透明?

这不起作用:

@State var show: Bool = false

var body: some View {
    VStack {
        Button(action: {
            self.show.toggle()
        }) {
            Text("button")
        }

        if show {
            Text("something")
                .animation(.easeInOut(duration: 0.5))
                .transition(.opacity)
        }
    }
}

这有效:

@State var show: Bool = false

var body: some View {
    VStack {
        Button(action: {
            withAnimation {
                self.show.toggle()
            }
        }) {
            Text("button")
        }

        if show {
            Text("something")
                // .animation(.easeInOut(duration: 0.5))
                .transition(.opacity)
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我想你想要这种效果

显示/隐藏并淡出:

Button(action: {
    withAnimation { self.show.toggle() }
}) {
    Text("button")
}

if (show)
{
    Text("something")
        .transition(.opacity).animation(.easeInOut(duration: 0.5))
}

淡入/淡出效果:

Text("something")
    .opacity(show ? 1 : 0)
    .transition(.opacity).animation(.easeInOut(duration: 0.5))