根据当前配色方案更改“使用 Apple 登录”按钮样式

Eri*_*edo 4 ios swift swiftui swiftui-environment

SignInWithAppleButton我在使用 SwiftUI时遇到一些问题signInWithAppleButtonStyle。我正在尝试根据用户当前的方案或它是否发生变化来更改按钮的颜色。这是 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
        }
    })
Run Code Online (Sandbox Code Playgroud)

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

mrj*_*sly 7

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

然后使用@Environment(\.colorScheme)创建if statement并导入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 }
        )
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我们可以编写更优雅的解决方案。基于上面 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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)