gpt4 book ai didi

SwiftUI:在创建 View 后动态更改 View 的过渡

转载 作者:行者123 更新时间:2023-12-04 13:33:47 24 4
gpt4 key购买 nike

我想更改 View 的过渡 动态 创建 View 后。我切换状态变量 isTransition1通过单击按钮在 transition1 之间切换和 transition2如下。但是,如果这些过渡之一是不透明度,则它不会按预期工作。更改过渡后立即删除的 View 始终保持其原始过渡。令人惊讶的是,如果我改变 transition2滑动,它将毫无问题地工作。要删除的 View 将使用新的过渡。有什么办法可以使不透明度在这里起作用吗?

let transition1 = AnyTransition.asymmetric(insertion: .move(edge: .trailing),
removal: .move(edge: .leading))

let transition2 = AnyTransition.opacity

struct Wrapper1<Content: View>: View {
let content: Content

var body: some View {
content
}
}

struct Wrapper2<Content: View>: View {
let content: Content

var body: some View {
content
}
}

struct TextView: View {
let count: Int
let color: Color

var body: some View {
ZStack {
color
.edgesIgnoringSafeArea(.all)
.frame(maxWidth: UIScreen.main.bounds.width,
maxHeight: UIScreen.main.bounds.height)

Text("Count: \(count)")
.font(.title)
.offset(y: -200)
}
}
}

struct ContentView: View {
@State private var count = 0
@State private var isTransition1 = false

var body: some View {
ZStack {
if count % 2 == 0 {
Wrapper1(content: TextView(count: count, color: Color.green)
.transition(isTransition1 ? transition1 : transition2))
} else {
Wrapper2(content: TextView(count: count, color: Color.red)
.transition(isTransition1 ? transition1 : transition2))
}

HStack(spacing: 100) {
Button(action: {
self.isTransition1.toggle()
}) {
Text("Toggle Transition").font(.title)
}

Button(action: {
withAnimation(.linear(duration: 2)) {
self.count += 1
}
}) {
Text("Increase").font(.title)
}
}
}
}
}

最佳答案

不确定我是否正确理解您尝试实现的效果,但尝试重置 View 层次结构(至少这肯定会重置过渡,因此它们不会相互影响):

  var body: some View {
ZStack {
if count % 2 == 0 {
Wrapper1(content: TextView(count: count, color: Color.green)
.transition(isTransition1 ? transition1 : transition2))
} else {
Wrapper2(content: TextView(count: count, color: Color.red)
.transition(isTransition1 ? transition1 : transition2))
}

HStack(spacing: 100) {
Button(action: {
self.isTransition1.toggle()
}) {
Text("Toggle Transition").font(.title)
}

Button(action: {
withAnimation(.linear(duration: 2)) {
self.count += 1
}
}) {
Text("Increase").font(.title)
}
}
}.id(isTransition1) // << here !!
}

关于SwiftUI:在创建 View 后动态更改 View 的过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63432189/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com