![](/img/trans.png)
[英]navigationBarItems “Type [view] cannot conform to 'View'; only struct/enum/class types can conform to protocols”
[英]Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols; calling functions with 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()
}
}
}
它还有@State private var play = false; 一个函数 playSound 是这样的:
static private func playSound()
{
WKInterfaceDevice.current().play(.failure)
}
我收到类型“()”不能符合“视图”的错误; 只有结构/枚举/类类型可以符合协议我认为这可能是我不理解结构在 Swift 中工作的方式。 我正在尝试使用计时器来触发播放声音功能。 这是我的 iOS 故事板应用程序timer = Timer.scheduledTimer(timeInterval: interval, target: click class, selector: #selector(clickClass.repeatSound), userInfo: clickClass, repeats: switchView.isOn)
在我的视图控制器类中的代码
你这样做:
if play
{
MyWatchView.self.playSound()
}
在只需要View
的上下文中。 该函数的返回类型是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()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.