动态更改icon

iOS10.3下,添加了新特性,可以动态更改icon.

UIApplication新增属性

//判断是否支持动态替换
@property (readonly, nonatomic) BOOL supportsAlternateIcons NS_EXTENSION_UNAVAILABLE("Extensions may not have alternate icons") API_AVAILABLE(ios(10.3), tvos(10.2));
//根据plist配置,替换自己想要的icon
- (void)setAlternateIconName:(nullable NSString *)alternateIconName completionHandler:(nullable void (^)(NSError *_Nullable error))completionHandler NS_EXTENSION_UNAVAILABLE("Extensions may not have alternate icons") API_AVAILABLE(ios(10.3), tvos(10.2));
//替换icon的时候根据该属性获取到当前被替换到显示的icon名称,例如你没换的时候就是nil,换了icon1,那么就显示icon1
@property (nullable, readonly, nonatomic) NSString *alternateIconName NS_EXTENSION_UNAVAILABLE("Extensions may not have alternate icons") API_AVAILABLE(ios(10.3), tvos(10.2));

替换方法

1.设置plist.在plist文件的'Icon files'(CFBundleIcons)下添加'CFBundleAlternateIcons'字段,与'Primary Icon'(CFBundlePrimaryIcon)平级.并填充icon信息.有多个就添加多个 key可以自定义,这个key是动态设置icon的唯一标识.

<key>CFBundleIcons</key>
<dict>
<key>CFBundleAlternateIcons</key>
<dict>
<key>Icon1</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>Icon1</string>
</array>
</dict>
<key>Icon2</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>watermark1_w</string>
</array>
</dict>
</dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>Icon-72</string>
</array>
</dict>
</dict>

2.icon图片要添加到资源中,大小没有要求,不一定是标准尺寸. 3.在需要更改icon的位置添加如下代码

if (![[UIApplication sharedApplication] supportsAlternateIcons])
{
NSLog(@"不支持动态替换icon");
return;
}
NSLog(@"icon not exist");
[[UIApplication sharedApplication] setAlternateIconName:@"Icon1" completionHandler:^(NSError * _Nullable error)
{
if (error)
{
NSLog(@"%@",error);
}
}];

成功后系统会弹出alert提示更改图标成功.

  • 注意这里的iconName不是图片名称,而是plist中设置的单个icon的key.

  • 启动时调用此方法无效,会自动被cancle.

  • 设置为nil时恢复默认图标