前言
前面的文章 iOS 开发入门 - 快速编写一个弹框动态库 dylib 已经写了安装 Xcode、Xcode 命令行工具、Homebrew、Idid、TheOS、MonkeyDev等、这次就跳过这些流程了、没看过的点击查看
首先打开Xcode 创建一个新项目
设置最低运行系统
暂时用不着、 直接注释
创建新文件
打开新创建的文件 并导入 UIKit 框架
#import <UIKit/UIKit.h>
使用 __attribute__((constructor)) 让程序加载时自动调用这个函数,这种构造函数在程序启动时会被自动执行,无需显式调用。
static void __attribute__((constructor)) tests(void) {
}
使用 Grand Central Dispatch (GCD) 在程序中将任务异步派发到主队列执行
dispatch_async(dispatch_get_main_queue(), ^{
});
创建一个 passwordAlert 静态变量来存储 UIAlertController 对象
static UIAlertController *passwordAlert;
赋值 passwordAlert 静态变量创建一个新的弹框
passwordAlert = [UIAlertController alertControllerWithTitle:@"验证密码" message:@"请输入密码完成验证" preferredStyle:UIAlertControllerStyleAlert];
[passwordAlert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"请在此处输入密码后提交";
textField.secureTextEntry = YES;
}];
添加一个取消按钮【关闭软件】
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"关闭软件" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
exit(0);
}];
[passwordAlert addAction:cancelAction];
添加一个验证按钮【验证密码】
UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"验证密码" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSString *inputPassword = passwordAlert.textFields.firstObject.text;
if ([inputPassword isEqualToString:@"123456"]) {
[passwordAlert dismissViewControllerAnimated:YES completion:nil];
} else {
if (inputPassword.length == 0) {
passwordAlert.message = @"请输入密码完成验证";
UIViewController *rootViewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
[rootViewController presentViewController:passwordAlert animated:YES completion:nil];
} else {
passwordAlert.message = @"您输入的密码不正确";
UIViewController *rootViewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
[rootViewController presentViewController:passwordAlert animated:YES completion:nil];
}
}
}];
[passwordAlert addAction:confirmAction];
以上验证密码逻辑 当输入密码为 123456 时才会关闭弹框 反之提示
最后 通过获取应用的根视图控制器来立即显示 passwordAlert
弹框
UIViewController *rootViewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
[rootViewController presentViewController:passwordAlert animated:YES completion:nil];
可能发生问题:在软件启动时立即弹框可能会出现不弹框的问题 出现此问题可以使用最简单粗暴的
dispatch_after 方法来
延迟弹框呈现 比如延迟 2 秒 下面为例子
UIViewController *rootViewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[rootViewController presentViewController:passwordAlert animated:YES completion:nil];
});
完工、附带效果图*3 感谢您花费数分钟或数秒钟的时间观看此文章
补充一下
上篇文章 iOS 开发入门 - 快速编写一个弹框动态库 dylib 忘记写 Code Signing Identity 设置了
写这篇文章编译的时候比较有空、所以自己编译注入了下测试效果、结果发现了[dog head][狗头保命]