如何在iOS 9应用程序中为静态UIApplicationShortcutItem指定自定义图标?

时间:2015-09-13 20:51:42

标签: ios ios9 3dtouch uiapplicationshortcutitem

我目前正在使用3D Touch为我的iOS 9应用实现主屏幕快速操作。我使用定义的UIApplicationShortcutIconType枚举中的现有系统图标进行了多项操作。

一个例子:

<dict>
    <key>UIApplicationShortcutItemIconType</key>
    <string>UIApplicationShortcutIconTypeSearch</string>
    <key>UIApplicationShortcutItemTitle</key>
    <string>Search for Parking</string>
    <key>UIApplicationShortcutItemType</key>
    <string>SEARCH</string>
</dict>

但是,对于其中一个操作,我想使用自定义图标。我已经尝试用我的图像资产的名称替换UIApplicationShortcutItemIconType字符串,但这不起作用。

使用UIApplicationShortcutIcon.iconWithTemplateImageName()对动态操作很容易,但此操作必须是静态的。

2 个答案:

答案 0 :(得分:37)

不使用UIApplicationShortcutItemIconType键,而是将其替换为UIApplicationShortcutItemIconFile键,然后提供图像文件或ImageAsset的名称。

像这样:

<dict>
    <key>UIApplicationShortcutItemIconFile</key>
    <string>MyCustomImageName</string>
</dict>

其余的按键可以保持不变。

答案 1 :(得分:22)

使用UIApplicationShortcutItemIconFile作为键和图像文件的名称(带或不带文件扩展名)作为字符串。例如:使用名为“lightning.png”的图像,您可以将以下内容添加到Info.plist ...

multipage

图像可以存储在项目树中或Assets.xcassets中。如果将图像存储在Assets.xcassets中,如果您将图像命名为与文件名不同的名称,请使用图像集名称。

您的图像文件需要是PNG(如果您需要透明度),方形,单色和35x35像素。多色图像基本上是黑色覆盖。

这是符合上述标准的测试图像:

lightning.png with transparent background 35x35px

只需将此图像另存为“lightning.png”,将其拖放到项目树中,然后使用Info.plist文件中的上述代码。

对于那些不习惯将Info.plist编辑为源代码的人来说,如果你在属性列表中原生地执行上述操作,上面的内容如下:

Info.plist

要将这些快捷方式附加到代码,请在AppDelegate.swift中执行此操作。添加以下内容:

<key>UIApplicationShortcutItems</key>
<array>
    <dict>
        <key>UIApplicationShortcutItemIconFile</key>
        <string>lightning</string>
        <key>UIApplicationShortcutItemTitle</key>
        <string>Search for Parking</string>
        <key>UIApplicationShortcutItemType</key>
        <string>SEARCH</string>
    </dict>
</array>

值得注意的是,UIApplicationShortcutItemType的约定并非全部大写(例如“SEARCH”),而是使用您的包标识符作为预修复:

func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {

    if shortcutItem.type == "SEARCH" {
        print("Shortcut item tapped: SEARCH")
        // go to SEARCH view controller
    }

}