SwiftUI使用Text时报No exact matches in call to initializer错误怎么解决
错误原因
SwiftUI的Text控件没有支持直接传入Double类型参数的初始化方法,你代码中直接把Double类型的rotation变量传入Text,系统无法匹配到对应的初始化器,因此触发报错。
解决方法
有两种常用的修复方案:
- 方案1:使用字符串插值将Double类型转为String类型传入,写法最简单:
把Text(rotation)替换为Text("\(rotation)") - 方案2:使用数值格式化控制显示精度,避免出现多位冗余小数,适配你Slider的0.1步长设置:
把Text(rotation)替换为Text(rotation, format: .number.precision(.fractionLength(1)))
修正后的完整代码
import SwiftUI struct ContentView: View { @State var rotation: Double = 0 var body: some View { VStack { VStack { Text("Hello, world!") .padding() Slider(value: $rotation, in: 0 ... 360, step: 0.1) .padding() // 替换为任意一种修复后的写法即可 Text(rotation, format: .number.precision(.fractionLength(1))) } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
内容的提问来源于stack exchange,提问作者GCMeccariello
相关产品推荐
相关产品推荐

