类型 '()' 不能符合 'View';只有 struct/enum/class 类型才能符合协议;使用 SwiftUI 调用函数

Der*_*ews 15 struct ios watchos swiftui

我有一个带有此堆栈的名为 MyWatchView 的 Swift UI 结构。

        VStack (alignment: .center)
        {
            HStack
            {
                Toggle(isOn: $play)
                {
                    Text("")


                }
                .padding(.trailing, 30.0)
                .hueRotation(Angle.degrees(45))
                if play
                {
                    MyWatchView.self.playSound()
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

它还有@State private var play = false; 一个函数 playSound 是这样的:

static private func playSound()
{
    WKInterfaceDevice.current().play(.failure)
}
Run Code Online (Sandbox Code Playgroud)

我收到类型“()”不能符合“视图”的错误;只有结构/枚举/类类型可以符合协议我认为这可能是我不理解结构在 Swift 中工作的方式。我正在尝试使用计时器来触发播放声音功能。这是我在我的 iOS 故事板应用程序中的视图控制器类中的代码timer = Timer.scheduledTimer(timeInterval: interval, target: click class, selector: #selector(clickClass.repeatSound), userInfo: clickClass, repeats: switchView.isOn)

Sam*_*Sam 14

你这样做:

if play
{
    MyWatchView.self.playSound()
}
Run Code Online (Sandbox Code Playgroud)

在只需要Views的上下文中。函数的返回类型是Void(or ()),这就是您收到错误的原因。


如果你想当您单击播放声音Toggle,你可能想使用Button,而不是:

Button(action: {
    MyWatchView.self.playSound()
}) {
    Text("")
}
Run Code Online (Sandbox Code Playgroud)

如果你想要一个Toggle(例如,更新一个Bool变量),你可以这样做:

Toggle(isOn: $play)
{
    Text("")
}
.padding(.trailing, 30.0)
.hueRotation(Angle.degrees(45))
.onTapGesture {
    MyWatchView.self.playSound()
}
Run Code Online (Sandbox Code Playgroud)