简体   繁体   English

在具有双 If 和 if else 条件的 SwiftUI 中,转换 animation 行为与预期不同

[英]Transition animation behavior is not as expected in SwiftUI with double If and if else conditional

I would like to know what's the difference or why I have a different behavior with my transition animation when I use two different blocks of if statements and when I use if-else statement expecting the same behavior, here some examples:我想知道当我使用两个不同的 if 语句块并且当我使用 if-else 语句期望相同的行为时,我的转换 animation 有什么不同或为什么会有不同的行为,这里有一些示例:

  • The following code works fine and the transition animation behave as expected:以下代码可以正常工作,并且转换 animation 的行为符合预期:
VStack {
   homeHeader
            
   columnTitles
            
    if !showPortfolio {
       allCoinsListView
          .transition(.move(edge: .leading))
    }

    if showPortfolio {
       portfolioListView
           .transition(.move(edge: .trailing))
    }
            
    Spacer(minLength: 0)
}
  • The transition animation doesn't behave as expected:过渡 animation 的行为不符合预期:
VStack {
  homeHeader
            
  columnTitles
            
  if !showPortfolio {
       allCoinsListView
         .transition(.move(edge: .leading))
   } else {
       portfolioListView
         .transition(.move(edge: .trailing))
   }
            
   Spacer(minLength: 0)
}

This is the ViewBuilder specifics:这是ViewBuilder的细节:

  1. in the first case it creates a view for each condition (so two views are present on screen, one in, one out with transition);在第一种情况下,它为每个条件创建一个视图(因此屏幕上存在两个视图,一进一出,带有过渡);
  2. in the second case it creates only one view (with replaceable content), so it does not work.在第二种情况下,它只创建一个视图(具有可替换的内容),所以它不起作用。

I found a solution for this issue.我找到了解决这个问题的方法。 The difference likely has to do with how the SwiftUI Result Builder translates the if-else statement into buildIf, buildEither, etc vs. how the if-else statements are translated.差异可能与SwiftUI Result Builder如何将if-else 语句转换为 buildIf、buildEither 等与 if-else 语句的转换方式有关。 See: https://jasonzurita.com/swiftui-if-statement/请参阅: https://jasonzurita.com/swiftui-if-statement/

If you explicitly define asymmetric transitions in the if-else statement :如果您在if-else 语句中明确定义不对称转换

VStack {
    homeHeader
    
    columnTitles
    
    if !showPortfolio {
        allCoinsListView
            .transition(.asymmetric(insertion: .move(edge: .leading),
                                    removal: .move(edge: .trailing)))
    } else {
        portfolioListView
            .transition(.asymmetric(insertion: .move(edge: .trailing),
                                    removal: .move(edge: .leading)))
    }
    
    Spacer(minLength: 0)
}

I found the answer to this issue thanks to this post: SwiftUI Switch Statement Transition Behavior is not as expected由于这篇文章,我找到了这个问题的答案: SwiftUI Switch Statement Transition Behavior is not as expected

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM