首先需要注意的是,动态更换图标需要在iOS10.3之后才可以使用
第一步、需要在info.plist中配置图标的一些信息,具体如下
根据自己的需求修改图标样式如下为info.plist中的配置,拿走不谢
<key>CFBundleIcons</key> <dict> <key>CFBundleAlternateIcons</key> <dict> <key>10.1</key> <dict> <key>UIPrerenderedIcon</key> <false/> <key>CFBundleIconFiles</key> <array> <string>Icon-29</string> <string>Icon-60</string> <string>Icon-Spotlight-40</string> <string>icon-1024</string> </array> </dict> <key>7.1</key> <dict> <key>UIPrerenderedIcon</key> <false/> <key>CFBundleIconFiles</key> <array> <string></string> </array> </dict> </dict> <key>CFBundlePrimaryIcon</key> <dict> <key>CFBundleIconName</key> <string></string> <key>CFBundleIconFiles</key> <array> <string></string> </array> <key>UIPrerenderedIcon</key> <false/> </dict> <key>UINewsstandIcon</key> <dict> <key>CFBundleIconFiles</key> <array> <string></string> </array> <key>UINewsstandBindingType</key> <string>UINewsstandBindingTypeMagazine</string> <key>UINewsstandBindingEdge</key> <string>UINewsstandBindingEdgeLeft</string> </dict> </dict>
第二步、需要执行代码去进行更换图标的操作,这种情况下会有弹框提示更换,点击确定会进行更换图标操作
- (void)setAppIconWithName:(NSString*)iconName {
if(@available(iOS10.3, *)) {
if (![[UIApplication sharedApplication] supportsAlternateIcons]) {
return;
}
}else{
// Fallback on earlier versions
}
if([iconNameisEqualToString:@""]) {
iconName =nil;
}
if(@available(iOS10.3, *)) {
[[UIApplication sharedApplication] setAlternateIconName:iconName completionHandler:^(NSError * _Nullable error) {
if(error) {
NSLog(@"更换app图标发生错误了 : %@",error);
}
}];
}else{
// Fallback on earlier versions
}
}
第三步、优化弹框,在用户无感知的情况下进行图标切换,需要通过runtime来处理此操作,写一个UIViewController扩展类,具体处理如下
+ (void)load{
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
MethodpresentM =class_getInstanceMethod(self.class,@selector(presentViewController:animated:completion:));
MethodpresentSwizzlingM =class_getInstanceMethod(self.class,@selector(dy_presentViewController:animated:completion:));
method_exchangeImplementations(presentM, presentSwizzlingM);
});
}
- (void)dy_presentViewController:(UIViewController*)viewControllerToPresentanimated:(BOOL)flagcompletion:(void(^)(void))completion {
if([viewControllerToPresentisKindOfClass:[UIAlertControllerclass]]) {
UIAlertController*alertController = (UIAlertController*)viewControllerToPresent;
if(alertController.title==nil&& alertController.message==nil) {
return;
}else{
[selfdy_presentViewController:viewControllerToPresentanimated:flagcompletion:completion];
return;
}
}
[selfdy_presentViewController:viewControllerToPresentanimated:flagcompletion:completion];
}
到这里完整的更换图标就可以了,亲测可用
网友评论