在教程中第 6 步中提供了如下的代码示例:
@State private var isPlaying = false
Button(action: { self.isPlaying.toggle() }) { Image(systemName: isPlaying ? "pause.circle.fill" : "play.circle.fill") .font(.system(size: 200)) .foregroundColor(.red) }
其中,$isPlaying 被标记为 @State 属性,该属性只能在 SwiftUI 的视图层次结构中使用。并且,按照教程中的描述,该示例应该在 ContentView 中使用。
如果您在使用这个示例时,产生了类似如下的编译错误:
Use of unresolved identifier '$isPlaying'
这个错误提示表明编译器无法识别 $isPlaying。这个错误的原因是,您可能将这个示例代码块放在了错误的层级结构中,并且没有正确设置相关的属性绑定。要消除这个错误,可以将这个示例代码块复制到 ContentView 的 body 属性中,并在 ContentView 中定义相应的状态属性:
struct ContentView: View { @State private var isPlaying = false
var body: some View {
Button(action: {
self.isPlaying.toggle()
}) {
Image(systemName: isPlaying ? "pause.circle.fill" : "play.circle.fill")
.font(.system(size: 200))
.foregroundColor(.red)
}
}
}
这个示例代码将 Button 和 Image 放置在 ContentView 的 body 属性中,并将 isPlaying 属性添加到了 ContentView 的状态中,以便正确定义。如果您成功地应用了这个解决方案,就可以再次尝试运行代码,并消除编译错误。