簡體   English   中英

SwiftUI:動畫期間的文本問題

[英]SwiftUI: Text issue during animations

我對涉及Text的動畫有問題。 基本上我需要更改文本並為其位置設置動畫。 看看下面這個簡單的例子:

import SwiftUI

struct ContentView: View {
    @State private var isOn = false
    @State private var percentage = 100

    var body: some View {
        ZStack {
            Text("\(percentage)")
                .font(.title)
                .background(Color.red)
                .position(isOn ? .init(x: 150, y: 300) : .init(x: 150, y: 100))
                .animation(.easeOut(duration: 1), value: isOn)

            VStack {
                Spacer()
                Button(action: {
                    self.isOn.toggle()

                    //just to make the issue happen
                    if self.percentage == 100 {
                        self.percentage = 0
                    } else {
                        self.percentage = 100
                    }
                }, label: {
                    Text("SWITCH")
                })
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

結果是:

在此處輸入圖片說明

這里有一些問題。 可能最煩人的是...我只想為Text的位置設置動畫,我不想為文本本身設置動畫,也不想為文本的寬度設置動畫。 有任何想法嗎? 謝謝你。

在按鈕上試試這個動作:

 Button(action: 
 {
   //just to make the issue happen
   if self.percentage == 100 
   {
     self.percentage = 0
   } 
   else 
   {
     self.percentage = 100
   }
   withAnimation(.easeInOut(duration: 1.0)) {
     self.isOn.toggle()
   }

 }, label: {
   Text("SWITCH")
 })

並從您的標簽中刪除該行

 .animation(.easeOut(duration: 1), value: isOn)

我還沒有測試它。

可能的替代方法是添加縮放因子,它取代截斷模式並提供不同的效果,在某些情況下可能更可取。

唯一需要的變化如下(當然可以修改因素)

Text("\(percentage)")
    .minimumScaleFactor(0.5)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM