看了很多文章的介紹,最后還是看官方文檔最清楚。
1.動態設置和靜態設置
動態設置就是在代碼中添加或更新shortcutItem.相關的類有
UIApplicationShortcutItem
、UIApplicationShortcutIcon
靜態設置是指在Info.plist文件中,用鍵值對的方式添加. 需要自己添加,xcode貌似不會自動提示key. - -|||
<key>UIApplicationShortcutItems</key>
<array>
<dict>
<key>UIApplicationShortcutItemIconFile</key>
<string>open-favorites</string>
<key>UIApplicationShortcutItemTitle</key>
<string>Favorites</string>
<key>UIApplicationShortcutItemType</key>
<string>com.mycompany.myapp.openfavorites</string>
<key>UIApplicationShortcutItemUserInfo</key>
<dict>
<key>key1</key>
<string>value1</string>
</dict>
</dict>
<dict>
<key>UIApplicationShortcutItemIconType</key>
<string>UIApplicationShortcutIconTypeCompose</string>
<key>UIApplicationShortcutItemTitle</key>
<string>New Message</string>
<key>UIApplicationShortcutItemType</key>
<string>com.mycompany.myapp.newmessage</string>
<key>UIApplicationShortcutItemUserInfo</key>
<dict>
<key>key2</key>
<string>value2</string>
</dict>
</dict>
</array>
2.區別
靜態設置是在應用安裝的時候完成加載的,而動態設置需要在運行到對應代碼時(runtime) 才加載,所以同時有靜態加載的Item和動態加載的Item時,靜態加載的Item會排在前面。
3.運用
文檔推薦對可以直接使用的一些功能進行靜態設置,而對于需要達到一些要求之后才能使用的Item就進行動態加載,并且可能一些靜態加載的Item在App使用之后可能出現功能或者顯示的變化,可以通過動態加載的方式進行更新。
UIApplicationShortcutItem *anExistingShortcutItem = [existingShortcutItems objectAtIndex:anIndex];
NSMutableArray <UIApplicationShortcutItem *> *updatedShortcutItems = [existingShortcutItems mutableCopy];
UIMutableApplicationShortcutItem *aMutableShortcutItem = [anExistingShortcutItem mutableCopy];
[aMutableShortcutItem setLocalizedTitle: @"New Title"];
[updatedShortcutItems replaceObjectAtIndex:anIndex withObject: aMutableShortcutItem];
[[UIApplication sharedApplication] setShortcutItems: updatedShortcutItems];
4.擴展:UIApplicationShortcutWidget
iOS 10中添加了UIApplicationShortcutWidget
這個key,用于在桌面使用3D Touch時顯示widget. 這個key只要寫在Info.plist中就可以了,它的值就設置為對應的widget的bound id.