簡體   English   中英

類型 '()' 不能符合 'View'; 只有 struct/enum/class 類型可以符合使用 swift ui 調用調用函數的協議

[英]Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols calling calling functions with swift ui

我有一個帶有此堆棧的名為 MyWatchView 的 SwiftUI 視圖:

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 Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols我認為這可能是我不理解結構在 Swift 中工作的方式。

你的 MyWatchView.self.playSound() 函數沒有返回一個視圖,因此你不能在你的 HStack 中使用它。

沒有看到你的完整代碼,我只能假設你想要做什么,但這是我的猜測:如果狀態變量 play 為真,你想執行 func playSound()?

你可以這樣做:

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

每當 State 變量 play 更改為 true 時,這將執行您的靜態 func。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM