ios - 类型 '()' 不能符合 'View' ;只有结构/枚举/类类型可以符合协议(protocol);使用 SwiftUI 调用函数

标签 ios struct swiftui watchos

我有一个名为 MyWatchView 的 Swift UI 结构和这个堆栈。

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


                }
                .padding(.trailing, 30.0)
                .hueRotation(Angle.degrees(45))
                if play
                {
                    MyWatchView.self.playSound()
                }
            }
        }

它还有@State private var play = false;还有一个函数 playSound 是这样的:
static private func playSound()
{
    WKInterfaceDevice.current().play(.failure)
}

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

最佳答案

你正在这样做:

if play
{
    MyWatchView.self.playSound()
}

在只有 View 的情况下s 是预期的。函数的返回类型是Void (或 () ),这就是您收到错误的原因。

如果您只想在单击 Toggle 时播放声音,您可能想使用 Button反而:

Button(action: {
    MyWatchView.self.playSound()
}) {
    Text("")
}

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

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

关于ios - 类型 '()' 不能符合 'View' ;只有结构/枚举/类类型可以符合协议(protocol);使用 SwiftUI 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60906835/

相关文章:

ios - 调用 viewDidLoad 时,单元格数据不会显示在 TableView 中

c++ - struct constructor会占用struct空间内的空间吗?

ios - SwiftUI - 导航栏后退按钮出现几分之一秒

swiftui - 如何从 Viewcontroller 中关闭 swiftUI?

ios - 在编辑时为了清晰起见,可以在 info.plist 中放置标记或队列吗?

ios - 在更多菜单中更改 UITabBar 色调颜色

c - 初始化结构并通过引用传递

c++ - 为什么偏爱数据结构对齐?

ios - 剪裁时使 SwiftUI 点击不会超出边界

javascript - 移动设备的屏幕宽度(android和ipod)