问题描述
我在使用 SwiftUI 的 SignInWithAppleButton
的 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
}
})
当 appleButtonWhite
更改值时,它会按原样呈现视图,因为状态正在更改。当我调试按钮时,它具有正确的 appleButtonWhite 值,但由于某种原因,样式永远不会改变。我不知道为什么。我使用常规按钮在我的代码中进行了许多样式更改,并且它可以根据不同的状态正常工作。有什么想法为什么 Apple 没有改变吗?
解决方法
我设法通过将 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 }
)
}
}
,
我们可以编写更优雅的解决方案。基于上面的 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)
}
}
}