1、需求:
產(chǎn)品設(shè)計APP要求在某些節(jié)日變化桌面的logo圖標(biāo),這里記錄下如何動態(tài)修改桌面圖標(biāo)的方法。
這里所說的方法是試用iOS13之前的系統(tǒng)版本,與iOS15之后“通過App Store切換圖標(biāo)”的方式不同
2、思想:
通過將不同的icon圖標(biāo)打到包內(nèi),并手動配置,然后通過業(yè)務(wù)代碼修改icon。動態(tài)修改的icon需要放在工程文件夾中不能放在Assets.xcassets里,默認的主icon還是可以放在Assets.xcassets中。

3、info.plist配置
加載完資源圖片后,還需要在info.plist中配置相應(yīng)的參數(shù),保證在切換logo時可以順利找到相應(yīng)的圖標(biāo)。
- 在
info.plist中添加Icon files(iOS 5)字段,類型為Dictionary; - 在
Icon files(iOS 5)內(nèi)添加一個Key = CFBundleAlternateIcons字段,類型為Dictionary; - 在
CFBundleAlternateIcons內(nèi)配置我們需要動態(tài)修改的icon,格式為:key = "圖片名稱",類型為字典,其中包含兩種類型字段,1)key=CFBundleIconFiles,類型為數(shù)組,數(shù)組內(nèi)包含要動態(tài)修改的圖片;2)key= UIPrerenderedIcon,類型為布爾類型,默認值為NO,也可以不添加此字段。 -
如果要配置多套ICON,那么需要添加不同名字、同規(guī)模尺寸的圖片,然后在Info.plist的CFBundleAlternateIcons內(nèi)添加新的一組數(shù)據(jù)。
<key>CFBundleIcons</key>
<dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconName</key>
<string></string>
<key>CFBundleIconFiles</key>
<array>
<string></string>
</array>
<key>UIPrerenderedIcon</key>
<false/>
</dict>
<key>CFBundleAlternateIcons</key>
<dict>
<key>iphone</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>iphone-58</string>
<string>iphone-80</string>
<string>iphone-120</string>
<string>iphone-180</string>
<string>iphone-1024</string>
</array>
<key>UIPrerenderedIcon</key>
<false/>
</dict>
</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>
PS:圖片的名稱需要跟
Info.plist里的CFBundleIconFiles配置的名稱匹配。setAlternateIconName:的參數(shù),需要跟Info.plist里的CFBundleAlternateIcons配置的key相同。
4、代碼調(diào)用
- OC代碼
if ([UIApplication sharedApplication].supportsAlternateIcons) {
[[UIApplication sharedApplication] setAlternateIconName:@"iphone" completionHandler:^(NSError * _Nullable error) {
if (error) {
NSLog(@"更換app圖標(biāo)發(fā)生錯誤了 : %@",error);
}
}];
}
- Swift代碼
if UIApplication.shared.supportsAlternateIcons {
UIApplication.shared.setAlternateIconName("iphone" ){ err in
if let error = err {
print(error)
} else {
print("成功了")
}
}
}
- 強制回到桌面代碼
UIApplication.shared.perform(#selector(NSXPCConnection.suspend))
- 恢復(fù)默認桌面圖標(biāo)
[[UIApplication sharedApplication] setAlternateIconName:nil completionHandler:nil];
