无法为表达式生成诊断;请提交一份错误报告



我正在尝试制作计算器,但当我尝试从数组中制作按钮时,我遇到了这个错误,我遵循了一些教程,然后它成功了,当我自己尝试时,代码无法按应有的方式编译。这是一些代码

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())
})
}

代码编译。我想让这个按钮充满活力,只是为了练习。

我想,因为您想要一个计算器,所以您试图用第二个ForEach创建一个网格。为了做到这一点,您需要放置一个[[String]],或者您正在使用的任何类型。但是使用CCD_ 3有一个简单得多的解决方案。

此外,你需要用你的视图修改器选择一个样式并坚持使用。可以在一行上运行,也可以使用多行。否则你会错过一些东西。我推荐多行代码,因为它使您的代码作为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)
)

}
}

最新更新