.onChange() - 无法将“Double”类型的值转换为预期的参数类型“()”

Joe*_*tto 1 xcode swift swiftui

我试图检测@State变量的更改以更新某些文本,但无法使其工作,因为.onChange修改器抛出此错误:

无法将“Double”类型的值转换为预期的参数类型“()”

struct CalcView: View {
    @State private var width = 0.0

    var body: some View {
        VStack {
            Button(action: {
                width += 1.0
            }, label: {
                Text("Increment width")
            })
        }
        .onChange(of: width) { // This line specifically 
            print("Width Changed")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

hus*_*gle 7

您使用 onChange 修饰符调用的闭包不接受任何参数,但 onChange 希望将 Double 传递给该闭包。尝试改成.onChange(of: width) {这样:

\n

.onChange(of: width) { newWidth in

\n