巧用 allowsHitTesting 自定义 SignInWithAppleButton

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

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

Swift 复制代码
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 的尺寸裁剪成我们需要的。

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

至于样式,我们首先想到的是将一个图片盖在 SignInWithAppleButton 之上,不过盖在上面的元素会阻断 SignInWithAppleButton 的点击事件。为了能够让 SignInWithAppleButton 继续拿到点击事件,我们需要屏蔽掉上层元素的点击事件。我们可以通过 allowsHitTesting 来实现。

Swift 复制代码
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

相关推荐
二流小码农1 小时前
鸿蒙开发:上传一张参考图片便可实现页面功能
android·ios·harmonyos
开心就好202517 小时前
UniApp开发应用多平台上架全流程:H5小程序iOS和Android
后端·ios
开心就好202520 小时前
免 Xcode 的 iOS 开发新选择?聊聊一款更轻量的 iOS 开发 IDE kxapp 快蝎
后端·ios
恋猫de小郭1 天前
Apple 的 ANE 被挖掘,AI 硬件公开,宣传的 38 TOPS 居然是"数字游戏"?
前端·人工智能·ios
东坡肘子1 天前
OpenClaw 不错,但我好像没有那么需要 -- 肘子的 Swift 周报 #125
人工智能·swiftui·swift
忆江南2 天前
iOS 深度解析
flutter·ios
没有故事的Zhang同学2 天前
05-主题|事件响应者链@iOS-应用场景与进阶实践
ios
FeliksLv2 天前
尝试给Lookin 支持 MCP
ios
没有故事的Zhang同学2 天前
01-研究系统框架@Web@iOS | JavaScriptCore 框架:从使用到原理解析
ios
CocoaKier4 天前
苹果谷歌商店:如何监控并维护用户评分评论
ios·google·apple