很难用语言描述我的问题。
我想让选择器表现得像那样。
但是当我改变浏览方向后,因为我已经设置了进出过渡,即使我将过渡更改为新的,视图仍然使用旧的消失。 (第一个和最后一个)
有什么办法可以解决这个问题吗?
这是代码
@State var translations:[String] = ["未知"]
@State var index = 0
@State var transition:AnyTransition = .asymmetric(insertion: .move(edge: .trailing), removal:.move(edge: .leading)).combined(with: .opacity)
var transTexts:some View{
HStack{
if(translations.count > 1){
Button {
if(index > 0){
transition = .asymmetric(insertion: .move(edge: .leading), removal:.move(edge: .trailing)).combined(with: .opacity)
disabled.toggle()
index -= 1
}
} label: {
Image(systemName:"arrowtriangle.backward.circle.fill")
}
.disabled(index == 0)
Text(translations[index])
.scroll()
.font(.body)
.id(index)
.disabled(disabled)
.transition(transition)
}
Spacer()
if(translations.count > 1){
Button {
if(index < translations.count-1){
transition = .asymmetric(insertion: .move(edge: .trailing), removal:.move(edge: .leading)).combined(with: .opacity)
disabled.toggle()
index += 1
}
} label: {
Image(systemName:"arrowtriangle.forward.circle.fill")
}
.disabled(index == translations.count - 1)
}
}
.animation(.default,value: index)
我不确定为什么会发生这种情况,但延迟
index
的更改对我有用。
transition = ...
DispatchQueue.main.asyncAfter(deadline: .now() + 0.001) {
index += 1 // or -= 1
}
我还建议使用
Bool
或枚举来编码其前进的方向,而不是 AnyTransition
。
工作代码:
@State var translations:[String] = ["Lorem Ipsum", "Foo Bar baz", "Something Else", "AAAAA", "BBBBB"]
@State var index = 0
@State var isForward = true
var body:some View{
VStack {
HStack{
if(translations.count > 1){
Button {
if(index > 0){
isForward = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.001) {
index -= 1
}
}
} label: {
Image(systemName:"arrowtriangle.backward.circle.fill")
}
.disabled(index == 0)
}
if translations.count > 0 {
Text(translations[index])
.font(.body)
.id(index)
.transition(
isForward ?
.asymmetric(insertion: .move(edge: .trailing), removal:.move(edge: .leading)) :
.asymmetric(insertion: .move(edge: .leading), removal:.move(edge: .trailing))
)
}
Spacer()
if(translations.count > 1){
Button {
if index < translations.count - 1 {
isForward = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.001) {
index += 1
}
}
} label: {
Image(systemName:"arrowtriangle.forward.circle.fill")
}
.disabled(index == translations.count - 1)
}
}
.animation(.default,value: index)
}
}