SwiftUI添加视图时提示Extra argument in call错误如何解决
问题根本原因
SwiftUI 的容器组件(VStack、HStack、ZStack、ScrollView 等)默认遵循ViewBuilder语法限制,最多只能承载10个直接子视图。你当前代码的 ScrollView 下正好有10个直接子元素:1个文本组件 + 3个输入框 + 6个骰子按钮,已经达到上限,所以新增任何组件都会触发「Extra argument in call」报错,和你猜测的「组件数量过多」的方向完全吻合。
解决方案
方案1:用 Group 对现有组件做逻辑分组
将同类型的组件包裹在Group中,Group 本身只算1个子视图,就能突破10个的限制,改动最小。示例改动如下:
var body: some View { VStack { ScrollView { // 第一组:状态展示文本 Group { Text("The Current Value Rolled is: \(RolledNumbersString.joined(separator: ", ")), with a Modifier of \(String(convert(Modifier, true))) rolling \(String(convert(NumRolledDie, false))) die, to get a total of \(String(Total)), \nYou also rolled a \(LastDie).") } // 第二组:输入框 Group { TextField("Enter Modifier...", text: $Modifier) .textFieldStyle(RoundedBorderTextFieldStyle()) TextField("How Many Die Rolled...\nMake sure this is greater then 1", text: $NumRolledDie) .textFieldStyle(RoundedBorderTextFieldStyle()) TextField("Enter Custom Die Value...", text: $CustomDie) .textFieldStyle(RoundedBorderTextFieldStyle()) } // 第三组:骰子按钮 Group { // 这里直接放你原有6个骰子按钮的代码即可 } // 现在可以自由新增其他组件,不会触发报错 Text("新增的测试文本") } } }
方案2:抽取重复组件为自定义子视图(更推荐)
你当前的6个骰子按钮逻辑高度重复,只有骰子面数的差异,完全可以抽取为独立的自定义View,既减少冗余代码,也能直接降低父容器的子视图数量:
// 抽取的通用骰子按钮组件 struct DiceRollButton: View { let diceSides: Int? // 自定义骰子传nil,固定面数传对应数值 let customDieInput: String let rollAction: () -> Void var body: some View { Button(action: rollAction) { Text(" ROLL THE DICE: \(diceSides == nil ? "D\(customDieInput)" : "D\(diceSides!)") ") .background( ZStack { Color.purple LinearGradient(gradient: Gradient(colors: [Color.white.opacity(0.3), Color.clear]), startPoint: .top, endPoint: .bottom) }) .foregroundColor(.black) .cornerRadius(21) .padding() } } }
抽取后原来的ScrollView下只需要调用这个自定义组件即可,子视图数量大幅减少,后续新增组件也不会触发上限报错。
内容的提问来源于stack exchange,提问作者Superbia
相关产品推荐
相关产品推荐

