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

Chr*_*ein 28 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>
Run Code Online (Sandbox Code Playgroud)

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

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

Chr*_*ein 37

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

像这样:

<dict>
    <key>UIApplicationShortcutItemIconFile</key>
    <string>MyCustomImageName</string>
</dict>
Run Code Online (Sandbox Code Playgroud)

其余的钥匙可以保持原样.

  • 来自https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/iPhoneOSKeys.html"图标应为方形,单色和35x35点,如这些模板文件中所示和所述在iOS人机界面指南中." (6认同)
  • 艾迪,注意我说点而不是像素.因此,这对应于35px乘35px 1x图像,70px乘70px 2x图像用于视网膜,以及105px乘105px 3x图像用于6+. (4认同)
  • 请注意,70x70也适用,并且在Retina显示屏上看起来要好得多. (2认同)

Jus*_*ely 24

使用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>
Run Code Online (Sandbox Code Playgroud)

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

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

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

lightning.png透明背景35x35px

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

对于那些不习惯将Info.plist编辑为源代码的人来说,如果你在属性列表中本地执行它,上面的内容应该是这样的:

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

}
Run Code Online (Sandbox Code Playgroud)

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

com.myapps.shortcut-demo.search
Run Code Online (Sandbox Code Playgroud)

  • 正确的尺寸是 `35pt` = `105 x 105 @3x` 和 `70 x 70 @2x` (2认同)