【发布时间】:2021-08-08 15:06:29
【问题描述】:
我的结果是模拟器死机了。
我的预期结果是让程序添加随机数,直到当我按下“非七”按钮时出现 7。
我的目标是完成这个挑战: *构建一个包含一个列表和下面三个按钮的 UI。
当第一个按钮被点击时:
将一个随机整数(从 1 到 10)添加到列表中。 如果您添加到列表中的整数不是 7,则继续将随机整数(从 1 到 10)添加到列表中,直到您将 7 添加到列表中。 点击第二个按钮时:
将列表中显示的所有整数加 1 点击第三个按钮时:
清除列表中的所有数字。
这是节目录制的链接: https://files.fm/f/t5trf3ww3
import SwiftUI
struct ContentView: View {
@State var numbers = [Int]()
var body: some View {
VStack {
List(numbers, id: \.self) { num in
Text(String(num))
}
HStack {
Button("Not Seven") {
var randNumber = 0
randNumber = Int.random(in: 0...10)
repeat{
numbers.append(randNumber)
}while randNumber != 7
}
Button("Add 1 to All") {
for index in 0...numbers.count - 1 {
numbers[index] += 1
}
}
Button("Delete") {
numbers.removeAll()
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
Group {
ContentView()
ContentView()
}
}
}
【问题讨论】:
-
我的猜测是它与
repeatwhile有关。如果你改变它会发生什么? -
另外,为什么你的
PreviewProvider中有两个ContentViews? -
将其更改为根目录下的 LazyVStack。 UI 跟不上,将其更改为 Lazy 意味着它只会显示您当前正在查看的内容。
标签: ios swift xcode swiftui ios-simulator