SwiftUI开发计算器动态按钮时出现Failed to produce diagnostic编译报错
错误原因
- 数据结构不匹配布局逻辑:你当前定义的
numbers是一维字符串数组,每个元素仅包含单个数字字符,你期望实现3个按钮为一行的布局,需要使用二维数组存储每行的按钮文本。 - 编译器类型推断失败:你编写的两层
ForEach遍历逻辑与一维数组不匹配,加上多层View嵌套超出SwiftUI的ViewBuilder类型推断阈值,因此抛出无明确信息的编译错误。
修复方案
将numbers修改为二维数组,调整遍历逻辑即可实现按行动态生成按钮的效果,修复后的完整代码如下:
struct ContentView: View { let value = """ modern calculator """ // 改为二维数组,每个子数组对应一行按钮 let numbers = [ ["7", "8", "9"], ["4", "5", "6"], ["1", "2", "3"] ] var body: some View { VStack{ VStack{ // 去掉无意义的.self Text(value) .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) { row in HStack{ Spacer(minLength: 13) // 第二层遍历当前行的每个按钮文本 ForEach(row, 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(.all) } }
内容的提问来源于stack exchange,提问作者Luka Šalipur
相关产品推荐
相关产品推荐

