如何自定义仅显示Apple图标的SignInWithAppleButton并保留核心逻辑
实现仅显示图标的Sign in with Apple按钮(保留原有逻辑)
SwiftUI的SignInWithAppleButton确实没有直接提供仅显示图标的配置选项,但我们可以通过桥接UIKit的ASAuthorizationAppleIDButton来实现——它原生支持.iconOnly样式,同时能完全保留你原有的onRequest和onCompletion逻辑。
步骤1:封装UIKit按钮为SwiftUI组件
创建一个UIViewRepresentable结构体,桥接原生按钮并处理授权流程:
import SwiftUI import AuthenticationServices struct IconOnlySignInWithAppleButton: UIViewRepresentable { typealias UIViewType = ASAuthorizationAppleIDButton let onRequest: (ASAuthorizationAppleIDRequest) -> Void let onCompletion: (Result<ASAuthorization, Error>) -> Void let style: ASAuthorizationAppleIDButton.Style init(style: ASAuthorizationAppleIDButton.Style = .white, onRequest: @escaping (ASAuthorizationAppleIDRequest) -> Void, onCompletion: @escaping (Result<ASAuthorization, Error>) -> Void) { self.style = style self.onRequest = onRequest self.onCompletion = onCompletion } func makeUIView(context: Context) -> ASAuthorizationAppleIDButton { let button = ASAuthorizationAppleIDButton(type: .signIn, style: style) button.addTarget(context.coordinator, action: #selector(Coordinator.handleButtonTap), for: .touchUpInside) return button } func updateUIView(_ uiView: ASAuthorizationAppleIDButton, context: Context) {} func makeCoordinator() -> Coordinator { Coordinator(parent: self) } class Coordinator: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding { let parent: IconOnlySignInWithAppleButton init(parent: IconOnlySignInWithAppleButton) { self.parent = parent } @objc func handleButtonTap() { let provider = ASAuthorizationAppleIDProvider() let request = provider.createRequest() parent.onRequest(request) let controller = ASAuthorizationController(authorizationRequests: [request]) controller.delegate = self controller.presentationContextProvider = self controller.performRequests() } func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) { parent.onCompletion(.success(authorization)) } func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) { parent.onCompletion(.failure(error)) } func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor { guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene, let mainWindow = windowScene.windows.first else { return ASPresentationAnchor() } return mainWindow } } }
步骤2:替换原有按钮使用
直接用封装好的组件替换原来的SignInWithAppleButton,传入你原有的逻辑:
IconOnlySignInWithAppleButton(style: .white) { request in print("Apple ID Request") AppleSignInManager.shared.requestAppleAuthorization(request) } onCompletion: { result in print("Apple ID Completion") handleAppleID(result) } .frame(width: 50, height: 50) // 按需调整图标尺寸,符合Apple设计规范
补充说明
- 可通过
style参数选择按钮风格:.white、.black、.whiteOutline,对应SwiftUI版本的样式 - 确保项目已在开发者后台配置Sign in with Apple能力,否则授权流程会失败
- 图标尺寸建议遵循Apple设计规范,50x50pt左右为常用尺寸
内容的提问来源于stack exchange,提问作者Zied Mcharek
相关产品推荐
相关产品推荐

