最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ios - Why is .transition not applied on SwiftUI Text view when text (and ID) change? - Stack Overflow

programmeradmin3浏览0评论

In the following example the text and with it the ID of the Text view changes, when the button is tapped. So SwiftUI should treat the Text view as new view due to the updated ID, should it? So why is the transition not triggerd?

struct TextTransitionView: View {
    @State private var text: String = "Hello, World!"
    
    private var textTransition: AnyTransition {
        .asymmetric(
            insertion: .move(edge: .bottom)bined(with: .opacity),
            removal: .move(edge: .top)bined(with: .opacity)
        )
    }
    
    var body: some View {
        VStack {
            Text(text)
                .transition(textTransition)
                .id(text)
            
            Button("Change Text") {
                self.text += "!"
            }
        }
    }
}

In the following example the text and with it the ID of the Text view changes, when the button is tapped. So SwiftUI should treat the Text view as new view due to the updated ID, should it? So why is the transition not triggerd?

struct TextTransitionView: View {
    @State private var text: String = "Hello, World!"
    
    private var textTransition: AnyTransition {
        .asymmetric(
            insertion: .move(edge: .bottom)bined(with: .opacity),
            removal: .move(edge: .top)bined(with: .opacity)
        )
    }
    
    var body: some View {
        VStack {
            Text(text)
                .transition(textTransition)
                .id(text)
            
            Button("Change Text") {
                self.text += "!"
            }
        }
    }
}
Share Improve this question edited Mar 18 at 16:36 Andrei Herford asked Mar 18 at 16:28 Andrei HerfordAndrei Herford 18.8k24 gold badges108 silver badges258 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Make it a newview every cycle:

struct TextTransitionView: View {
    @State private var text: String = "Hello, World!"
    
    private var textTransition: AnyTransition {
        .asymmetric(
            insertion: .move(edge: .bottom)bined(with: .opacity),
            removal: .move(edge: .top)bined(with: .opacity)
        )
    }
    
    var body: some View {
        VStack {
            Text(text)
                .transition(textTransition)
                .id(text)  // Ensures the Text view has a new identity

            Button("Change Text") {
                withAnimation {
                    self.text += "!"
                }
            }
        }
    }
}
发布评论

评论列表(0)

  1. 暂无评论