ShortcutItem
iPhone 11 之前,有一种主屏交互方式称之为 3D Touch,现在已经改为 Haptic Touch。 它是一种立体触控技术,可感应不同的触控压力。通过该技术可以给 App 设置最多 4 个不同的 ShortcutItem(快捷操作菜单),实现方式分为静态和动态两种。
- 静态配置通过 Info.plist 文件。
<key>UIApplicationShortcutItems</key>
<array>
<dict>
<key>UIApplicationShortcutItemIconType</key>
<string>UIApplicationShortcutIconTypeSearch</string>
<key>UIApplicationShortcutItemSubtitle</key>
<string>副标题</string>
<key>UIApplicationShortcutItemTitle</key>
<string>标题</string>
<key>UIApplicationShortcutItemType</key>
<string>搜索</string>
</dict>
...
</array>
- 动态配置通过代码设置。
extension AppDelegate {
func shortcutItems() {
// 图标
let icon1 = UIApplicationShortcutIcon(systemImageName: "qrcode.viewfinder") // 系统图片
let icon2 = UIApplicationShortcutIcon(templateImageName: "settings") // 自定义图片
let icon3 = UIApplicationShortcutIcon(type: .search) // 系统类型
// 菜单
let item1 = UIApplicationShortcutItem(type: "1", localizedTitle: "扫描", localizedSubtitle: nil, icon: icon1, userInfo: nil)
let item2 = UIApplicationShortcutItem(type: "2", localizedTitle: "设置", localizedSubtitle: nil, icon: icon2, userInfo: nil)
let item3 = UIApplicationShortcutItem(type: "3", localizedTitle: "搜索", localizedSubtitle: nil, icon: icon3, userInfo: nil)
// 设置
UIApplication.shared.shortcutItems = [item1, item2, item3]
}
}
- 点击事件响应。
// iOS13之前,使用AppDelegate的代理方法
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
if shortcutItem.type == "1" {
window?.rootViewController?.view.backgroundColor = .red
} else if shortcutItem.type == "2" {
window?.rootViewController?.view.backgroundColor = .green
} else if shortcutItem.type == "3" {
window?.rootViewController?.view.backgroundColor = .blue
}
}
// iOS13之后,AppDelegate的代理方法不会被调用,需要使用SceneDelegate的代理方法
func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
if shortcutItem.type == "1" {
window?.rootViewController?.view.backgroundColor = .red
} else if shortcutItem.type == "2" {
window?.rootViewController?.view.backgroundColor = .green
} else if shortcutItem.type == "3" {
window?.rootViewController?.view.backgroundColor = .blue
}
}
UIMenu
- UIMenu 在 iOS 13 中引入,可以很方便的创建程序菜单和上下文菜单。
import UIKit
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// 显示工具条
navigationController?.isToolbarHidden = false
// 菜单绑定到UIBarButtonItem(iOS 14的构造函数)
let addNewItem = UIBarButtonItem(systemItem: .add, primaryAction: nil, menu: createMenu())
// 放到工具条
toolbarItems = [addNewItem]
}
func createMenu() -> UIMenu {
// 第一个菜单
let favorite = UIAction(title: "Favorite", image: UIImage(systemName: "heart.fill")) { _ in
print("favorite")
}
// 第二个菜单
let share = UIAction(title: "Share", image: UIImage(systemName: "square.and.arrow.up.fill")) { _ in
print("share")
}
// 第三个菜单
let delete = UIAction(title: "Delete", image: UIImage(systemName: "trash.fill"), attributes: [.destructive]) { _ in
print("delete")
}
// 创建菜单组
let menuActions = [favorite, share, delete]
// 创建UIMenu
let addNewMenu = UIMenu(children: menuActions)
return addNewMenu
}
}
- iOS 14 中引入
UIDeferredMenuElement
,允许异步地创建 UIMenu,可以动态配置菜单的内容。
import UIKit
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// 放到导航条
navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .add, primaryAction: nil, menu: createMenu())
}
func createMenu() -> UIMenu {
// 应该是是通过网络获取,这里直接从Bundle加载
let menuItemsForUser = Bundle.main.decode([RemoteItem].self, from: "menu.json")
// 创建UIDeferredMenuElement
let dynamicElements = UIDeferredMenuElement { completion in
// 创建UIAction
let actions = menuItemsForUser.map { item in
UIAction(title: item.title, image: UIImage(systemName: item.icon)) { _ in
print("\(item.title) tapped")
}
}
// 一定要调用completion处理
completion(actions)
}
return UIMenu(children: [dynamicElements])
}
}
// 菜单Model
struct RemoteItem: Codable {
let title: String
let icon: String
}
// 加载文件并转Model
extension Bundle {
func decode<T: Decodable>(_ type: T.Type, from file: String) -> T {
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to find \(file) in bundle.")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) from bundle.")
}
guard let model = try? JSONDecoder().decode(T.self, from: data) else {
fatalError("Failed to decode \(file) from bundle.")
}
return model
}
}
JSON内容如下:
[
{
"title": "Favorite",
"icon": "heart.fill"
},
{
"title": "Share",
"icon": "square.and.arrow.up.fill"
},
{
"title": "Delete",
"icon": "trash.fill"
}
]
Context Menus
- WWDC 2019 推出了上下文菜单(Context Menus),也是通过按压的方式触发,不同于 3D Touch(Haptic Touch),Context Menus 一般用于 App 内菜单的设置。
- 如果要启用上下文菜单,需要创建一个
UIContextMenuInteraction
并将其添加给某个触发的 UIView,然后指定 delegate,在代理方法创建 UIMenu 并返回UIContextMenuConfiguration
即可。
import UIKit
class ViewController: UIViewController {
// 需要打开User Interaction
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// 创建UIContextMenuInteraction
let interaction = UIContextMenuInteraction(delegate: self)
// 添加UIContextMenuInteraction
// 换成其他UIView皆可
imageView.addInteraction(interaction)
}
}
// 代理方法
extension ViewController: UIContextMenuInteractionDelegate {
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
// 第一个菜单
let favorite = UIAction(title: "Favorite", image: UIImage(systemName: "heart.fill")) { action in
print("favorite")
}
// 第二个菜单
let share = UIAction(title: "Share", image: UIImage(systemName: "square.and.arrow.up.fill")) { action in
print("share")
}
// 第三个菜单
let delete = UIAction(title: "Delete", image: UIImage(systemName: "trash.fill"), attributes: [.destructive]) { action in
print("delete")
}
// 返回UIContextMenuConfiguration
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in
UIMenu(children: [favorite, share, delete])
}
}
}