我對 Swift 相當陌生,我正在嘗試生成元素的 HStack(將在進度條中使用)并能夠使用按鈕添加元素。我不確定是否應該在 ForEach(1..<Variable) 部分使用變數或使用其他方法。這是我到目前為止的代碼,但它不起作用。
struct ContentView: View {
@State var fill : CGFloat = 0
@State var NumberOfCircles : Int = 0 var body: some View {
HStack(spacing:100) {
ForEach(0..<NumberOfCircles){ _ in
MyShape()
}
Button(action: {NumberOfCircles = 5}, label: {
Text("Button")
})
}
uj5u.com熱心網友回復:
ForEach在 SwiftUI 中需要一個恒定的范圍來回圈。但是,正如錯誤所暗示的那樣,如果您遵守Identifiable或使用ForEach(_:id:content:)并提供明確的內容,id那就很高興了。所以試試這個:
struct ContentView: View {
@State var fill: CGFloat = 0
@State var NumberOfCircles: Int = 0
var body: some View {
HStack(spacing: 20) {
ForEach(0..<NumberOfCircles, id: \.self){ _ in // <-- here
MyShape()
}
Button(action: {NumberOfCircles = 5}){
Text("Button")
}
}
}
}
uj5u.com熱心網友回復:
我不確定你的問題是什么,但我測驗了這段代碼并且它有效:
struct ContentView: View {
@State var numberOfCircles = 1
var body: some View {
VStack {
HStack {
ForEach(0..<numberOfCircles, id:\.self) { _ in
Circle()
.frame(width: 30, height: 30)
}
}
Button { numberOfCircles = 5 } label: {
Text("Add Circles")
}
}
}
}
順便說一句,Swift 中變數的命名約定是駝峰命名法。這意味著宣告一個變數你應該命名它numberOfCircles ,而不是NumberOfCircles . 第一個大寫字母保留用于命名類、結構和協議。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/330935.html
標籤:变量 迅捷 进度条 堆栈 swiftui-foreach
