iOS 10.3 如何更换 app 图标

iOS 10.3 开放了更换 app 图标的 API,核心方法是下面这个:javascript

func setAlternateIconName(_ alternateIconName: String?, 
    completionHandler: ((Error?) -> Void)? = nil)复制代码

这是官方文档,可是你还须要在 info.plist 里面填一些东西才能让它起做用,这部分官方注释内容在这里
html

但 info.plist 如何填写这部分读起来仍是有些晦涩,一时可能搞不清楚如何操做,下面作个示范。java

Assets.xcassets

info.plist

<key>CFBundleIcons</key>
<dict>
    <key>CFBundleAlternateIcons</key>
    <dict>
        <key>blackBgColor</key>
        <dict>
            <key>CFBundleIconFiles</key>
            <array>
                <string>blackBgColor</string>
            </array>
            <key>UIPrerenderedIcon</key>
            <false/>
        </dict>
    </dict>
    <key>CFBundlePrimaryIcon</key>
    <dict>
        <key>CFBundleIconFiles</key>
        <array>
            <string>AppIcon60x60</string>
        </array>
    </dict>
</dict>复制代码

如图,Primary Icon 字段写为 AppIcon60x60 是由于这里 xcassets 里面我只导入了 60pt@2x 和 60pt@3x 的图片资源,这里选为 60 是由于对于 iPhone,60pt 的图片资源图标所需最高质量,更低分辨率的版本系统会自动压缩以展现。git

blackBgColor 是个人用于替换原生图标的图片资源。文件名须要和 info.plist 中保持一致(注意 info.plist 中用到了两次 "blackBgColor"),同时这也是你在代码中设置图标时,须要给 API 传入的参数。一样是 60pt@2x 和 60pt@3x 的图片资源,文件不经过 Assets.xcassets 添加进来,而是直接放到目录中。github

若是你须要支持 iPad,建议这里使用 83.5pt(iPad Pro)的图片资源。另外还有些其余关于在 iPad 上替换图标的注意事项,在这里有说明,注意咱们这里在 info.plist 里面所用的 key 是 CFBundleIcons,还有另一个 key 是 CFBundleIcons~ipadapp

替换图标部分的代码就超级简单了:ide

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func changeAppIcon(_ sender: Any) {

        if UIApplication.shared.supportsAlternateIcons {
            print("you can change this app's icon")
        }else {
            print("you cannot change this app's icon")
            return
        }

        if let name = UIApplication.shared.alternateIconName {
            // CHANGE TO PRIMARY ICON
            UIApplication.shared.setAlternateIconName(nil) { (err:Error?) in
                print("set icon error:\(String(describing: err))")
            }
            print("the alternate icon's name is \(name)")
        }else {
            // CHANGE TO ALTERNATE ICON
            UIApplication.shared.setAlternateIconName("blackBgColor") { (err:Error?) in
                print("set icon error:\(String(describing: err))")
            }
        }
    }

}复制代码

这是上述全部内容的完整 demo 地址ui

screentshot0

screentshot1
相关文章
相关标签/搜索