登录
推荐 文章 Go 技术 课程 下载 专题 AI
首页 >  文章 >  软件教程

巧用 allowsHitTesting 自定义 SignInWithAppleButton

时间:2026-08-20 23:38:30 202浏览 收藏

最近在做一个新项目,需要使用 Sign in with Apple。由于这是是一个纯 SwiftUI 项目,因此我们首先考虑使用的是 Apple 官方的 SignInWithAppleButton 组件。

相较于传统的 Sign in with Apple API,SignInWithAppleButton 继承了 SwiftUI 组件的特性,API 特别简单,一个方法就能搞定 UI 展示。

SignInWithAppleButton(.signUp) { request in
    request.requestedScopes = [.fullName, .email]
} onCompletion: { result in
    print(result)
}
.signInWithAppleButtonStyle(.whiteOutline)

唯一美中不足的是,这个 Button 默认提供的 Style 只有三种,而且 Button 的尺寸也不能完全自定义,有最小宽度。

  • Black

  • White

  • White with outline

通过查看官方的 Human Interface Guidelines ,我们可以发现,官方其实还提供了其他的设计样式,例如更加常见的 icon only,但是目前 SignInWithAppleButton 并不支持这些样式,也不支持自定义样式(修改按钮的 content),SignIn​With​Apple​Button​.Style 也不支持自定义。

既然如此,我们就需要想办法曲线救国。

首先要解决的,是SignInWithAppleButton的尺寸问题。当给SignInWithAppleButton设定frame width时,一旦width小于某个值,SignInWithAppleButton就不再缩小了,这应该是内部为保证效果设置了最小宽度。为了便于布局,我们可以通过frame + clipped来强制将SignInWithAppleButton的尺寸裁剪成所需的大小。

SignInWithAppleButton(.signUp) { request in
    request.requestedScopes = [.fullName, .email]
} onCompletion: { result in
    print(result)
}
.frame(width: 32, height: 32)
.clipped()

那样式方面呢?我们最初的想法是把一个图片覆盖在SignInWithAppleButton上面。但问题来了,盖在上面的元素会把SignInWithAppleButton的点击事件给阻断。要想让SignInWithAppleButton还能接收到点击事件,就得把上层元素的点击事件给屏蔽掉。这事儿可以通过allowsHitTesting来实现。

ZStack {
    SignInWithAppleButton(.signUp) { request **in******
        request.requestedScopes = [.fullName, .email]
    } onCompletion: { result **in******
        print(result)
    }
    Image(.sign)
        .allowsHitTesting(false)
}
.frame(width: 32, height: 32)
.clipped()

这样,我们就得到了一个自定义样式的 SignInWithAppleButton

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>