我创建了一个自定义登录视图。我在另一个视图中使用该视图。我希望使用它的视图能够在按钮上设置某种颜色。我尝试通过在初始化中传递颜色来进行此操作,并且能够使它起作用。这感觉不太像swiftui风格。我尝试添加一个方法来代替,然后调用该方法,代码似乎可以运行,但实际上并没有改变颜色。我的问题是我是否使用方法正确执行此操作,这是最好的方法还是应该回到使用init或其他方法。谢谢。
自定义登录视图: ''' 公共结构LoginView:查看{ @ObservedObject var keyboardHandler:KeyboardFollower
select beer, group_concat(distinct name)
from bpb
group by beer
having count(distinct name) > 1
}
'''
我的其他观点: ''' struct ContentView:查看{
@State var username: String = ""
@State var password: String = ""
@Binding var presentingLoginModal: Bool
@ObservedObject var userDefaultsManager = UserDefaultsManager()
let loginService: SoCoLoginService
let defaults = UserDefaults.standard
@State var loginTextButtonColor: Color = Color.blue
public init(loginService: SoCoLoginService, presentingLoginModal: Binding<Bool>) {
self.keyboardHandler = KeyboardFollower()
self.loginService = loginService
self._presentingLoginModal = presentingLoginModal
}
public var body: some View {
VStack(content: {
TextField("Username", text: $username)
.autocapitalization(UITextAutocapitalizationType.none).textFieldStyle(RoundedBorderTextFieldStyle())
SecureField("Password", text: $password) {
self.loginUser()
}
.autocapitalization(UITextAutocapitalizationType.none)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button(action: self.loginUser) {
HStack {
Text("Log In")
.font(.body)
.bold()
.foregroundColor(loginTextButtonColor)
}
}
.disabled(username.isEmpty || password.isEmpty)
.padding()
Toggle(isOn: self.$userDefaultsManager.useFaceID) {
Text("Use Face ID/Touch ID")
}
})
.onAppear {
if self.userDefaultsManager.useFaceID {
let context = LAContext()
context.localizedCancelTitle = "Enter Username/Password"
var error: NSError?
if context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) {
let reason: String
if (context.biometryType == LABiometryType.faceID) {
reason = "Unlock using Face ID"
} else if (context.biometryType == LABiometryType.touchID) {
reason = "Unlock using Touch ID"
} else {
reason = "Log in to your account"
}
context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason ) { success, error in
if success {
do {
let credentials = try self.loginService.getCredentialsInKeychain()
self.username = credentials.username
self.password = credentials.password
self.loginUser()
} catch KeychainError.unhandledError(let status) {
print("Unhandled error of: " + status.description)
} catch KeychainError.noPassword {
print("No password in keychain")
} catch {
print("Unexpected error.")
}
} else {
print(error?.localizedDescription ?? "Failed to authenticate")
}
}
}
}
}
.padding(.bottom, keyboardHandler.keyboardHeight)
.padding()
}
}
'''