一、準備好icon圖標 然后放到項目中 如圖所示
WechatIMG243.jpeg
注意:1、圖片一定不要放到 Assets.xcassets 里面
2、icon圖片的名稱可以隨意取
3、icon圖片可以為一張 也可以為多少張(因為適配 所以我這里是多張 按照蘋果的尺寸來設計的圖片)
二、配置 Info.plist
截屏2022-06-23 上午10.08.56.png
2441655950296_.pic.jpg
如上圖
最后照如圖配置
WechatIMG245.jpeg
此時配置完成 ,
注意:1、Icon files (iOS 5) 這個鍵 最好用我上面的方式來添加 因為里面有默認的兩個鍵值 如果自己創建則是空的(當然自己創建也可以 但是字母一定不要寫錯)
2、主要的鍵值:CFBundleIconFiles(一定不要錯)
UIPrerenderedIcon(一定不要錯)
3、圖片對應的名稱 一定要與項目中的圖片名稱一致
三、代碼配置
- (void)changeAppIconWithName:(NSString *)iconName {
if (![[UIApplication sharedApplication] supportsAlternateIcons]) {
return;
}
if ([iconName isEqualToString:@""]) {
iconName = nil;
}
[[UIApplication sharedApplication] setAlternateIconName:iconName completionHandler:^(NSError * _Nullable error) {
if (error) {
NSLog(@"更換app圖標發生錯誤了 : %@",error);
}else{
NSLog(@"更換成功");
}
}];
}
這里的 iconName 就是你 Info.plist 里面配置的 name 如圖
WechatIMG246.jpeg
注意:名稱一定要對應
到此 項目配置完成
但是 此時你會發現 每次更換圖標就會彈出一個提示框 更換圖標用戶就會有感知,
四、利用runtime的方法交換 來攔截彈框事件,實現方法轉換,從而去掉彈框 做到無感知
具體做法,創建一個 UIViewController的 Category(分類)
創建方式如圖
[圖片上傳中...(截屏2022-06-23 上午10.30.28.png-90fb6e-1655951577112-0)]
WechatIMG248.jpeg
然后具體代碼:如下
//
// UIViewController+Category.m
// ChangeIcon
// 這個目的是攔截替換圖標時的彈框
// Created by 馮闖 on 2022/6/23.
//
#import "UIViewController+Category.h"
#import <objc/runtime.h>
@implementation UIViewController (Category)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method presentM = class_getInstanceMethod(self.class, @selector(presentViewController:animated:completion:));
Method presentSwizzlingM = class_getInstanceMethod(self.class, @selector(dismissAlertViewController:animated:completion:));
//runtime方法交換,通過攔截彈框事件,實現方法轉換,從而去掉彈框
method_exchangeImplementations(presentM, presentSwizzlingM);
});
}
- (void)dismissAlertViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)animated completion:(void (^)(void))completion {
if ([viewControllerToPresent isKindOfClass:[UIAlertController class]]) {
UIAlertController *alertController = (UIAlertController *)viewControllerToPresent;
if (alertController.title == nil && alertController.message == nil) {
return;
}
}
[self dismissAlertViewController:viewControllerToPresent animated:animated completion:completion];
}
@end
到此 所有配置已經完成
注意:建議使用真機測試,模擬器可能會一直報錯 更換圖標不成功
我這邊使用模擬器報如下錯誤(但是真zh)
使用模擬器 如下
WechatIMG249.jpeg
The requested operation couldn’t be completed
because the feature is not supported.