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

相关推荐
符哥20083 小时前
Swift 开发 iOS App 过程中写自定义控件的归纳总结
ios·cocoa·swift
pop_xiaoli3 小时前
effective-Objective-C 第二章阅读笔记
笔记·学习·ios·objective-c·cocoa
未来侦察班12 小时前
一晃13年过去了,苹果的Airdrop依然很坚挺。
macos·ios·苹果vision pro
锐意无限18 小时前
Swift 扩展归纳--- UIView
开发语言·ios·swift
符哥200818 小时前
用Apollo + RxSwift + RxCocoa搭建一套网络请求框架
网络·ios·rxswift
文件夹__iOS1 天前
AsyncStream 进阶实战:SwiftUI 全局消息流极简实现
ios·swiftui·swift
2501_916008891 天前
深入解析iOS机审4.3原理与混淆实战方法
android·java·开发语言·ios·小程序·uni-app·iphone
忆江南1 天前
Flutter深度全解析
ios
山水域1 天前
Swift 6 严格并发检查:@Sendable 与 Actor 隔离的深度解析
ios
楚轩努力变强1 天前
iOS 自动化环境配置指南 (Appium + WebDriverAgent)
javascript·学习·macos·ios·appium·自动化