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