巧用 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

相关推荐
疯狂的程序猴16 小时前
Flutter应用代码混淆完整指南:Android与iOS平台配置详解
后端·ios
SY.ZHOU17 小时前
移动端架构体系(五):终篇总结
flutter·ios·系统架构·安卓·鸿蒙
用户794572239541321 小时前
【AFNetworking】OC 时代网络请求事实标准,Alamofire 的前身
objective-c·swift
Digitally1 天前
如何不用 iTunes 将 iPhone 备份到移动硬盘?
ios·iphone
sysinside1 天前
Cisco Catalyst 9000 IOS XE 26.1.1 GA - 思科 Catalyst 9000 交换产品系列 IOS XE 系统软件
ios·cisco
低保和光头哪个先来1 天前
解决 ios 使用 video 全屏未铺满页面问题
前端·javascript·vue.js·ios·前端框架
报错小能手1 天前
SwiftUI 框架 认识 SwiftUI 视图结构 + 布局
ui·ios·swift
2501_915921431 天前
HTTP和HTTPS协议全面解析:技术原理与安全应用
安全·http·ios·小程序·https·uni-app·iphone
悟空爬虫-彪哥1 天前
VRCFaceTracking安装和iPhone面捕配置教程,有bug
ios·bug·iphone
想个名字想老半天1 天前
uni离线打包实现 ios 支付StoreKit 2,其实没有想象中那么复杂,不需要写原生插件,不需要转 uts
macos·ios·cocoa