這是測驗代碼:
import SwiftUI
struct ContentView: View {
@State private var pad: Bool = false
@State private var showDot: Bool = true
var body: some View {
VStack {
Button {showDot.toggle()} label: {Text("Toggle Show Dot")}
Spacer().frame(height: pad ? 100 : 10)
Circ(showDot: showDot)
Spacer()
}.onAppear {
withAnimation(.linear(duration: 3).repeatForever()) {pad = true}
}
}
}
struct Circ: View {
let showDot: Bool
var body: some View {
Circle().stroke().frame(height: 50).overlay {if showDot {Circle().frame(height: 20)}}
}
}
碰巧在我切換之后showDot,點圈又不在筆畫圈的中心了!我怎樣才能解決這個問題?Circ視圖已給出,我無法更改該視圖!
uj5u.com熱心網友回復:
編輯
如果您可以隱藏視圖,請參閱解決方案 1,這是首選。如果需要重新構建視圖,請參見解決方案 2。
解決方案 1
將if條件替換為當is時為.opacity()1 的修飾符。showDottrue
這樣,點不會完全消失,它就在那里,但你看不到它。您將切換可見性,而不是視圖本身。
像這樣:
@State private var pad: Bool = false
@State private var showDot: Bool = true
var body: some View {
VStack {
Button {
showDot.toggle()
} label: {
Text("Toggle Show Dot")
}
Spacer()
.frame(height: pad ? 100 : 10)
Circle().stroke()
.frame(height: 50)
.overlay {
Circle()
.frame(height: 20)
.opacity(showDot ? 1 : 0) // <- Here
}
Spacer()
}
.onAppear {
withAnimation(.linear(duration: 3).repeatForever()) {pad = true}
}
}
解決方案 2
您可以用計時器替換影片。每次觸發時,它都會通過改變高度來移動整個視圖Spacer()。
// These variables will track the position and moving direction of the dot
@State private var pos: CGFloat = 0
@State private var movingUp = false
@State private var showDot: Bool = true
// This variable will change the position
// This is a dummy iniatialization, the .onAppear modifier sets the real timer
@State private var timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in }
var body: some View {
VStack {
Button {
showDot.toggle()
} label: {
Text("Toggle Show Dot")
}
Spacer()
.frame(height: pos)
Circle().stroke()
.frame(height: 50)
.overlay {
if showDot {
Circle().frame(height: 20)
}
}
Spacer()
}
.onAppear {
// The timer interval will define the speed
timer = Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true) { _ in
moveCircle()
}
}
}
private func moveCircle() {
if movingUp {
if pos <= 0 {
pos = 0
movingUp = false
} else {
pos -= 1
}
} else {
if pos >= 100 {
pos = 100
movingUp = true
} else {
pos = 1
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/475493.html
