iOS13 中的 ContextMenuConfigurationForRowAt

ContextMenuConfigurationForRowAt in iOS13

在WWDC19季的这个视频中,Modernizing Your UI for iOS 13,这个方法是创建上下文菜单,但是我在使用的时候报错:

@available(iOS 13.0, *)
func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
    let actionProvider = (suggestedActions: [UIMenuElement])-> UIMenu? // in this line i got an error {
        let editMenu = UIMenu(title: "Edit...", children: [
        UIAction(title: "Copy") {},
        UIAction(title: "Duplicate") {}
        ])
        return UIMenu(children: [
        UIAction(title: "Share") {},
        editMenu,
        UIAction(title: "Delete", style: .destructive) {}
        ])
    }

    return UIContextMenuConfiguration(identifier: "unique-ID" as NSCopying,
                                      previewProvider: nil,
                                      actionProvider: actionProvider)
}

错误出现在行 -> UIMenu? 中并显示 Expected type after '->'。谁能帮我解决一下?

您有很多语法错误:

func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
    let actionProvider: UIContextMenuActionProvider = { _ in
        let editMenu = UIMenu(title: "Edit...", children: [
            UIAction(title: "Copy") { _ in },
            UIAction(title: "Duplicate") { _ in }
        ])
        return UIMenu(title: "Title", children: [
            UIAction(title: "Share") { _ in },
            editMenu
        ])
    }

    return UIContextMenuConfiguration(identifier: "unique-ID" as NSCopying, previewProvider: nil, actionProvider: actionProvider)
}

请注意,某些 API 在 WWDC 之后发生了变化,您应该考虑像上面的代码一样更新它们。您可以查看 Kyle Bashour 撰写的综合 Guide to iOS Context Menus

示例:

func makeContextMenu() -> UIMenu {
    let rename = UIAction(title: "Rename Pupper", image: UIImage(systemName: "square.and.pencil")) { action in
        // Show rename UI
    }

    // Here we specify the "destructive" attribute to show that it’s destructive in nature
    let delete = UIAction(title: "Delete Photo", image: UIImage(systemName: "trash"), attributes: .destructive) { action in
        // Delete this photo 
    }

    // The "title" will show up as an action for opening this menu
    let edit = UIMenu(title: "Edit...", children: [rename, delete])

    let share = UIAction(...)

    // Create our menu with both the edit menu and the share action
    return UIMenu(title: "Main Menu", children: [edit, share])
}

func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
    return UIContextMenuConfiguration(identifier: nil, previewProvider: nil, actionProvider: { suggestedActions in

        // "puppers" is the array backing the collection view
        return self.makeContextMenu(for: self.puppers[indexPath.row])
    })
}