swift - 类型 '()' 不能符合 'View' ;只有 struct/enum/class 类型可以符合使用 swift ui 调用调用函数的协议(protocol)

标签 swift struct swiftui func watchos

我有一个名为 MyWatchView 的 SwiftUI View 和这个堆栈:

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)
}
我收到一个错误 Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols我认为这可能是我在 Swift 中的结构工作方式中不理解的东西。

最佳答案

您的 MyWatchView.self.playSound() 函数没有返回 View ,因此您不能在 HStack 中使用它。

没有看到你的完整代码,我只能假设你想做什么,但这是我的猜测:如果状态变量 play 为真,你想执行 func playSound()?

你可以这样做:

@State private var play = false {
    willSet {
        if newValue {
            WKInterfaceDevice.current().play(.failure)
        }
    }
}

每当 State 变量 play 更改为 true 时,这将执行您的静态函数。

关于swift - 类型 '()' 不能符合 'View' ;只有 struct/enum/class 类型可以符合使用 swift ui 调用调用函数的协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60815821/

相关文章:

c - header 未找到 typedef 的结构

ios - 向后滑动失败时,SwiftUI 导航栏项目变得困惑

swift - 如何在 Ventura 13.3.1 中使用 SwiftUI 将图像设置为 MacCatalyst 上的菜单标签

ios - 如何在 SwiftUI 中实现协议(protocol)和委托(delegate)

ios - NSKeyValueObservation 不起作用,Swift 4

ios - SecItemCopyMatching 返回 errSecItemNotFound

C:与字符串一起保存结构的动态数组

具有关联值的 Swift 枚举,在调用中得到 "missing argument label ' 数组”

swift 4 |正在引用数据库文件进行 SQLite 查询 "unable to open database file"

c++ - 在 C++ 中访问 C 结构