iOS开发如何为UIButton设置Touch ID/Face ID系统内置图标
解决方案
首先明确:Apple没有对外开放Touch ID、Face ID对应的官方内置图标调用API,无法直接为UIButton赋值系统原生图标,你可以按照以下步骤实现需求,同时兼容iOS 7及以上系统:
1. 准备图标资源
提前准备适配1x、2x、3x分辨率的指纹、人脸图标素材,导入到Xcode项目的Assets.xcassets中,分别命名为touch_id_icon和face_id_icon。
提示:图标样式尽量遵循Apple的人机交互规范,避免因样式不符合要求被App Store审核驳回。
2. 生物识别类型判断逻辑
引入LocalAuthentication框架,编写方法判断当前设备支持的生物识别类型:
import LocalAuthentication import UIKit // 返回值说明:0=不支持生物识别,1=支持Touch ID,2=支持Face ID func currentBiometricType() -> Int { let authContext = LAContext() var authError: NSError? // 先判断设备是否支持生物识别验证 guard authContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError) else { return 0 } // biometryType仅在iOS 11及以上版本可用 if #available(iOS 11.0, *) { switch authContext.biometryType { case .touchID: return 1 case .faceID: return 2 default: return 0 } } else { // iOS 11以下仅存在支持Touch ID的设备,直接返回1 return 1 } }
兼容注意:
LocalAuthentication框架从iOS 8开始引入,如果你需要兼容iOS 7,需要在项目中将该框架的引用类型设置为Optional,iOS 7设备调用该方法会直接返回0,你可以自行补充密码登录等备用逻辑。
3. 给UIButton设置对应图标
let biometricType = currentBiometricType() let authButton = UIButton(type: .custom) // 根据识别类型设置对应图标 switch biometricType { case 1: authButton.setImage(UIImage(named: "touch_id_icon"), for: .normal) case 2: authButton.setImage(UIImage(named: "face_id_icon"), for: .normal) default: // 不支持生物识别的设备可以隐藏按钮或设置其他图标 authButton.isHidden = true } // 后续可以继续设置按钮frame、点击事件等其他属性
内容的提问来源于stack exchange,提问作者TurboPascal
相关产品推荐
相关产品推荐

