我有一个名为 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/