如何Rectangle通過分配系結屬性來控制影片重復與否isRepeatAnimation?
我期望的是,在分配trueto之后isRepeatAnimation,邊框寬度從 5.0 到 0.0 來回影片,并且在分配falseto之后重復影片關閉isRepeatAnimation。
import SwiftUI
struct ContentView: View {
@Binding var isRepeatAnimation: Bool
@State var lineWidth: CGFloat = 5
var body: some View {
Rectangle()
.stroke(Color.blue, style: StrokeStyle(lineWidth: lineWidth))
.frame(width: 100, height: 100)
.animation(isRepeatAnimation ? repeatAnimation : Animation.easeInOut, value: lineWidth)
}
var repeatAnimation: Animation {
Animation.easeInOut.repeatForever(autoreverses: true)
}
}
struct ContentViewPreviewer: View {
@State var repeated = false
var body: some View {
VStack {
ContentView(isRepeatAnimation: $repeated)
Button("Toggle") {
repeated.toggle()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentViewPreviewer()
}
}
uj5u.com熱心網友回復:
要停止重復影片,我們應該將其替換為默認影片,并且可以切換線寬。
使用 Xcode 13.4 / iOS 15.4 測驗

以下是主要修復:
Rectangle()
.stroke(Color.blue, style: StrokeStyle(lineWidth: isRepeatAnimation ? 0 : lineWidth))
.frame(width: 100, height: 100)
.animation(isRepeatAnimation ? repeatAnimation : Animation.default, value: isRepeatAnimation)
專案中完整的測驗模塊
uj5u.com熱心網友回復:
如果目的是讓線寬從 5 變為 0 再到 5 并停止,這可能是一個解決方案。如果目的是手動停止影片,請閱讀 Asperi 的解決方案。
您可以設定兩次影片,首先是在持續時間的前半部分將線寬從 5 更改為 0,然后在后半部分從 0 更改為 5。您可以使用兩個命令控制此行為:
- 上
.animation(),包括一個預定義的(duration:) - 在更改布爾變數時,使用從 0 更改回 5
DispatchQueue.main.asyncAfter()
這是示例代碼:
struct ContentView: View {
@Binding var animate: Bool
@State private var lineWidth = 5.0
var body: some View {
Rectangle()
.stroke(Color.blue, style: StrokeStyle(lineWidth: lineWidth))
// Instead of repeating, make it with a pre-defined duration.
// The value here (0.25) is half of the total duration
.animation(.easeInOut(duration: 0.25), value: lineWidth)
.frame(width: 100, height: 100)
// Change the line width when animate changes
.onChange(of: animate) { _ in
// Make it zero immediately
lineWidth = 0
// On the second half of the duration, make it 5 again
DispatchQueue.main.asyncAfter(deadline: .now() 0.25) {
lineWidth = 5
}
}
}
}
struct ContentViewPreviewer: View {
@State var animate = false
var body: some View {
VStack {
ContentView(animate: $animate)
Button("Toggle") {
animate.toggle()
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/483604.html
