巧用 allowsHitTesting 自定义 SignInWithAppleButton

148 阅读2分钟

最近在做一个新项目,需要使用 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

image.png

  • White

image.png

  • White with outline

image.png

通过查看官方的 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

image.png