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

32

我正在使用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个回答

44

不要使用UIApplicationShortcutItemIconType键,改用UIApplicationShortcutItemIconFile键,然后提供您的图像文件或ImageAsset的名称。

就像这样:

<dict>
    <key>UIApplicationShortcutItemIconFile</key>
    <string>MyCustomImageName</string>
</dict>
其余的密钥可以保持原样。

我一直无法让它正常工作。你有一个可用的图像示例吗?这个图像需要特定的尺寸吗?你使用了什么文件名<string> - pkamb
7
图标应为正方形,单色,大小为35x35点,如这些模板文件所示,并根据iOS人机界面指南所述。 - Chris Allwein
2
请注意,70x70同样适用,并且在Retina显示屏上看起来更好。 - Eddy Verbruggen
5
注意,我说的是点数而不是像素。因此,这对应着一个35 x 35像素的1倍图像,一个70 x 70像素的2倍视网膜图像,以及一个105 x 105像素的3倍视网膜图像适用于iPhone 6+。 - Chris Allwein
@ChrisAllwein 我下载了一组图案,它们的尺寸不同。第一个尺寸是70像素乘以70像素,第二个尺寸是104像素乘以104像素。104乘以104是错误的吗? - Alexander Khitev
自定义图标正在显示,但只有黑色。而图标是蓝色的。我错在哪里了? - Chandresh

25

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

<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>

图片可以存储在项目树或Assets.xcassets中。如果您将图像存储在Assets.xcassets中,并且希望将集合命名与文件名不同,则使用图像集名称。

您的图像文件需要是PNG格式(如果您想要透明度),单色,正方形,大小为35x35像素。多色图像基本上会获得黑色覆盖。

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

lightning.png with transparent background 35x35px

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

对于那些不熟悉将 Info.plist 编辑为源代码的人,以下是在 Property List 中原生编辑的方法:

Info.plist

要将这些快捷方式附加到代码中,可以在 AppDelegate.swift 中完成。添加以下内容:

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

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

}

值得注意的是 UIApplicationShortcutItemType 的约定并不全是大写字母(例如:“SEARCH”),而是使用您的包标识符作为前缀:

com.myapps.shortcut-demo.search

实际上,@3x 图像的正确尺寸为 104 x 104,而 @2x 图像的正确尺寸为 70 x 70 - iOS.Lover
2
正确的尺寸为 35pt = 105 x 105 @3x70 x 70 @2x - stevo.mit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接