macOS中SignInWithAppleButton忽略frame设置占满视图的问题
macOS SwiftUI「用Apple登录」按钮无法自定义尺寸的解决办法
在macOS 14.0 + Xcode 15环境下,使用原生SwiftUI的SignInWithAppleButton时,按钮会无视frame尺寸设置,自动占据整个父视图空间,尝试fixedSize修饰符也无法解决问题。
用户原代码如下:
SignInWithAppleButton( .continue, onRequest: { request in request.requestedScopes = [.email] }, onCompletion: { result in switch result { case let .success(authorization): guard let appleIDCredentials = authorization .credential as? ASAuthorizationAppleIDCredential else { return } print( ">>> DEBUG: SignInWithAppleButton Auth Credential Ready - ", appleIDCredentials) case let .failure(error): print(">>> DEBUG: SignInWithAppleButton Auth Failed - ", error) } }) .border(Color.red) .frame(height: 30.0)
问题截图:

可行的解决方法
目前这属于macOS SwiftUI的已知兼容性问题,可通过以下两种方式规避:
方法1:用容器视图限制尺寸
将SignInWithAppleButton嵌套在HStack或VStack这类容器中,给容器设置目标尺寸,再让按钮填充容器空间:
HStack { SignInWithAppleButton( .continue, onRequest: { request in request.requestedScopes = [.email] }, onCompletion: { result in // 处理回调逻辑 } ) .frame(maxWidth: .infinity, maxHeight: .infinity) } .frame(height: 30) .border(.red)
方法2:使用缩放修饰符
通过scaleEffect调整按钮整体大小,配合fixedSize固定布局:
SignInWithAppleButton( .continue, onRequest: { request in request.requestedScopes = [.email] }, onCompletion: { result in // 处理回调逻辑 } ) .scaleEffect(0.7) // 根据需求调整缩放比例 .fixedSize() .border(.red)
内容的提问来源于stack exchange,提问作者XYZ
相关产品推荐
相关产品推荐

