【发布时间】:2022-01-07 07:42:02
【问题描述】:
我正在尝试制作计算器,但是当我尝试从数组制作按钮时出现此错误,我遵循了一些教程,然后它工作了,当我自己尝试时,代码不会按应有的方式编译。 这是一些代码
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(number, id:\.self){这里number不是必需的数组。你根本不需要这个内部 ForEach,删除它并使用Text(number)创建按钮。