【问题标题】:Extraneous Argument with Binding in SwiftUISwiftUI 中绑定的无关参数
【发布时间】:2021-04-02 04:35:09
【问题描述】:

我在操场上使用 SwiftUI 进行绑定,这是一个非常简单的代码

struct Car:View {
    var kar = "????"
    @Binding var startAnimation: Bool = false
    var body: some View {
        HStack {
            Spacer()
            Text(kar)
                .font(.custom("Arial", size: 100))
                .offset(x: self.startAnimation ? 0 - UIScreen.main.bounds.width + 100: 0)
        }
    }
}

但是 Playground 给出了一个错误,上面写着“Extraneous Argument Label”,我确实认为没有问题,尤其是当我使用 Xcode 编码时。那么有没有办法破解它或者我错过了什么??

【问题讨论】:

    标签: swiftui swift-playground


    【解决方案1】:

    你不能或者你不应该给 Binding 直接值,它绑定数据,你应该像在代码中一样使用 State



    与状态:

    import SwiftUI
    
    struct CarView: View {
        
        @State private var startAnimation: Bool = Bool()
        
        var body: some View {
            
            VStack {
                
                Text("?")
                    .font(Font.system(size: 100))
                    .offset(x: startAnimation ? 50.0 - UIScreen.main.bounds.width/2 : UIScreen.main.bounds.width/2 - 50.0)
                
                Button("Drive!") { startAnimation.toggle() }
                    .font(Font.headline)
                    .padding()
                
            }
            .animation(.easeIn(duration: 3.0), value: startAnimation)
            
        }
    }
    

    带绑定:

    import SwiftUI
    
    struct ContentView: View {
        
        @State private var startAnimation: Bool = Bool()
        
        var body: some View {
            
            VStack {
                
                CarView(startAnimation: $startAnimation)
                
                Button("Drive!") {
                    
                    startAnimation.toggle()
                }
                .font(Font.headline)
                .padding()
                
            }
            .animation(.easeIn(duration: 3.0), value: startAnimation)
            
        }
    }
    
    struct CarView: View {
    
        @Binding var startAnimation: Bool
        
        var body: some View {
            
            Text("?")
                .font(Font.system(size: 100))
                .offset(x: startAnimation ? 50.0 - UIScreen.main.bounds.width/2 : UIScreen.main.bounds.width/2 - 50.0)
    
        }
    }
    

    【讨论】:

    • 我确实使用了状态,就像在源代码中一样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 2021-07-29
    相关资源
    最近更新 更多