我正在嘗試制作計算器,但是當我嘗試從陣列制作按鈕時出現此錯誤,我遵循了一些教程,然后它起作用了,當我自己嘗試時,代碼將無法編譯。這是一些代碼
struct ContentView: View {
let value = """
modern
calculator
"""
let numbers = [ "7", "8", "9",
"4", "5", "6",
"1", "2", "3" ]
var body: some View {
VStack{
VStack{
Text(value.self)
.fontWeight(.thin)
.multilineTextAlignment(.trailing)
.frame(width: 416, height: 420)
.font(.system(size: 70))
.foregroundColor(Color.white)
}.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading).background(Color.blue)
VStack{
Spacer(minLength: 48)
VStack{
ForEach(numbers, id:\.self) {
number in
HStack{
Spacer(minLength: 13)
ForEach(number, id:\.self){
num in
Button(action: {}, label: {
Text(num).font(.largeTitle).fontWeight(.thin)
.frame(width: 50, height: 50)
.foregroundColor(Color.black)
.background(Color.white)
.clipShape(Circle())
})
}
}
}
}
}.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading).background(Color.black)
}.edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)
}
}
當我去掉這部分時,錯誤在第 20 行:
ForEach(number, id:\.self){
num in
Button(action: {}, label: {
Text(num).font(.largeTitle).fontWeight(.thin)
.frame(width: 50, height: 50)
.foregroundColor(Color.black)
.background(Color.white)
.clipShape(Circle())
})
}
代碼編譯。我想讓這個按鈕充滿活力,只是為了練習。
uj5u.com熱心網友回復:
我猜想是因為你想要一個計算器,所以你試圖用第二個ForEach. 為此,您需要放置 a[[String]]或您正在使用的任何型別。但是使用LazyVGrid().
此外,您需要使用視圖修飾符選擇一種樣式并堅持使用。要么在一行上運行它們,要么使用多行。否則你會錯過一些東西。我會推薦多行,因為它使您的代碼作為 SwiftUI 初學者易于閱讀。
有很多關于制作計算器的教程,我會遵循它們。處理按鈕按下和生成十進制數字可能比您想象的要困難。但是,對于您的 UI 代碼:
struct ContentView: View {
let value = """
modern
calculator
"""
// Added a "." as you will need that button.
let calcButtons = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "."]
let columns = [
// Using 3 grid items forces there to be 3 columns
GridItem(.adaptive(minimum: 80)),
GridItem(.adaptive(minimum: 80)),
GridItem(.adaptive(minimum: 80))
]
var body: some View {
VStack{
Text(value.self)
.fontWeight(.thin)
.multilineTextAlignment(.trailing)
.font(.system(size: 70))
.foregroundColor(Color.white)
LazyVGrid(columns: columns, spacing: 20) {
ForEach(calcButtons, id: \.self) { calcButton in
Text(calcButton)
.fontWeight(.thin)
.font(.system(size: 70))
.foregroundColor(Color.white)
.background(
// Colored red so you can see the size of the buttons. If you remove this, your button
// will be the width of the text which varies making the buttons hard to tap.
// Change the color to .clear to make a hidden background.
Color.red
.frame(width: 80, height: 80)
)
}
}
}
.background(Color.blue
.edgesIgnoringSafeArea(.all)
)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370544.html
