简体   繁体   中英

Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols; calling functions with SwiftUI

I have a Swift UI struct called MyWatchView with this stack.

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


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

It also has @State private var play = false; And a function playSound like this:

static private func playSound()
{
    WKInterfaceDevice.current().play(.failure)
}

I am getting an error of Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols I think this is probably something that I am not understanding in the way structs work in Swift. I am trying to use a timer to trigger the play sound function. This is my code in my View Controller Class from my iOS storyboard app timer = Timer.scheduledTimer(timeInterval: interval, target: click class, selector: #selector(clickClass.repeatSound), userInfo: clickClass, repeats: switchView.isOn)

You are doing this:

if play
{
    MyWatchView.self.playSound()
}

in a context where only View s are expected. The return type of the function is Void (or () ), which is why you are getting the error.


If you want to just play a sound when you click the Toggle , you probably want to use a Button instead:

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

If you want a Toggle (eg, to update a Bool variable), you can do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM