1

我对 SwiftUISignInWithAppleButtonsignInWithAppleButtonStyle. 我正在尝试根据用户的当前方案或更改按钮的颜色来更改按钮的颜色。这是 iOS 14 和 SwiftUI:

@Environment(\.colorScheme) var currentScheme
@State var appleButtonWhite = false

VStack{
SignInWithAppleButton(
                .signUp,
                onRequest: { request in              
                    request.requestedScopes = [.fullName, .email]
                },
                onCompletion: { result in
                    switch result {
                    case .success (let authResults):
                        print("Authorization successful.")
       
                    case .failure (let error):
                        print("Authorization failed: " + error.localizedDescription)
                    }
                }
            )
            .frame(minWidth: 0, maxWidth: .infinity)
            .signInWithAppleButtonStyle(appleButtonWhite ? .white : .black)
}
.onChange(of: currentScheme, perform: { (scheme) in
        if scheme == .light
        {
            appleButtonWhite = false
        }
        else
        {
            appleButtonWhite = true
        }
    })

appleButtonWhite更改值时,由于状态正在更改,它会按照应有的方式呈现视图。当我调试按钮时,它具有正确的 appleButtonWhite 值,但由于某种原因,样式永远不会改变。我不知道为什么。我在我的代码中使用常规按钮进行了许多样式更改,并且它可以根据不同的状态正常工作。任何想法为什么Apple不会改变?

4

2 回答 2

2

我设法通过移动SignInWithAppleButton到它自己的视图来解决这个问题,没有signInWithAppleButtonStyle

然后使用@Environment(\.colorScheme)create anif statement并使用 .import 导入SignInWithAppleButtonView样式signInWithAppleButtonStyle

import SwiftUI
import AuthenticationServices

struct ContentView: View {
    
    @Environment(\.colorScheme) var currentScheme
    
    var body: some View {
        if self.currentScheme == .light {
            SignInWithAppleButtonView()
                .signInWithAppleButtonStyle(.black)
        } else {
            SignInWithAppleButtonView()
                .signInWithAppleButtonStyle(.white)
        }
    }
}

struct SignInWithAppleButtonView: View {
    var body: some View {
        SignInWithAppleButton(
            .signUp,
            onRequest: {_ in },
            onCompletion: {_ in }
        )
    }
}
于 2021-01-05T16:19:29.227 回答
0

我们可以编写更优雅的解决方案。基于上面的 mrjohnsly 回答

这是一个解释如何有效使用 Swift 视图的资源https://developer.apple.com/wwdc21/10022

struct ContentView: View {
    @Environment(\.colorScheme) var currentScheme
    
    var body: some View {
        VStack {
            SignInWithAppleButton { request in
                // request handeling
            } onCompletion: { result in
                // result handeling
            }
            .signInWithAppleButtonStyle(currentScheme == .light ? .black : .white) // <- here
            .frame(width: 250, height: 45, alignment: .center)
        }
    }
}
于 2021-06-18T13:50:20.937 回答