gpt4 book ai didi

ios - .onAppear 是否导致文本在 SwiftUI 中消失?

转载 作者:行者123 更新时间:2023-12-01 19:29:25 28 4
gpt4 key购买 nike

我正在做一个简单的倒计时。我期望发生的是First计入 0 ,然后 Second计入 0 .当语句切换到 else block 时,HStack 文本在 Canvas 中消失。为什么会发生这种情况?

import SwiftUI

struct TestCountdown: View {
@State var first = 5
@State var second = 5
@State var totalDuration = 30
var body: some View {
VStack {
Text("\(totalDuration)")
if (first > 0) && (second > 0) {
HStack {
TestCode(number: $first, title: "First")
Spacer()
TestCode(number: $second, title: "Second")
}
}
}
.onAppear {
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
if self.totalDuration > 0 {
self.totalDuration -= 1

if self.first > 0 {
self.first -= 1
} else {
self.second -= 1
}
}
}
}
}
}

struct TestCode: View {
@Binding var number: Int
@State var title: String
var body: some View {
VStack {
Text(title)
.font(.system(size: 20, weight: .medium, design: .rounded))
Text("\(number)")
.font(.system(size: 30, weight: .medium, design: .rounded))
}
.frame(minWidth: 50, maxWidth: .infinity)
}
}

最佳答案

这意味着您的 HStack将在 时显示两个 firstsecond > 0:

if (first > 0) && (second > 0) {
HStack {
...
}
}
如果要显示 HStack要么 其中 > 0 你可以这样做:
if first > 0 || second > 0 { ... }
请参阅 Apple 文档:
  • BasicOperators
  • 关于ios - .onAppear 是否导致文本在 SwiftUI 中消失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64000608/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com