iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📲

[Swift 5] Quickly create long-press menus for TableView cells with ContextMenuSwift

に公開

This is a guide on how to use ContextMenuSwift, a library that makes it easy to create the menus commonly seen in many apps when long-pressing cells in a CollectionView or TableView.

Environment

  • macOS Big Sur 11.3
  • Xcode 12.4
  • Swift 5
  • ContextMenuSwift 0.0.8

Library Information

ContextMenuSwift

https://github.com/umerjabbar/ContextMenuSwift

Installation

Add the following to your Podfile:

pod 'ContextMenuSwift'

Then run pod install.

Examples from GitHub



Implementation

Import

First, import it into the CollectionView or TableView where you want to use it.
In this case, I will proceed with a TableView, so please replace it according to your own project.

HogeTableViewController.swift
import ContextMenuSwift

Extension Setup

Next, extend ContextMenuDelegate using an extension to set the behavior when the context menu is displayed.

HogeTableViewController.swift
// MARK: ContextMenuDelegate
extension HogeTableViewController: ContextMenuDelegate {
    
    /**
        Executed when a context menu option is selected
        - Parameters:
            - contextMenu: Presumably the context menu itself
            - cell: The cell **of the selected context menu**
            - targetView: The source view of the context menu
            - item: The selected context item (contains title, image, etc.)
            - index: The coordinates **of the selected context item**
        - Returns: Unclear (probably true if successful...?)
     */
    func contextMenuDidSelect(_ contextMenu: ContextMenu,
                              cell: ContextMenuCell,
                              targetedView: UIView,
                              didSelect item: ContextMenuItem,
                              forRowAt index: Int) -> Bool {
        
        print("Context menu's", index, "th cell was selected!")
	print("That cell contains the text:", item.title, "!")
        
        // The sample returned true, so let's try returning true for now
        return true
        
    }
    
    /**
        Executed when a context menu option is selected
        - Parameters:
            - contextMenu: Presumably the context menu itself
            - cell: The cell **of the selected context menu**
            - targetView: The source view of the context menu
            - item: The selected context item (contains title, image, etc.)
            - index: The coordinates **of the selected context item**
     This version does not return a value
      (The difference from the returning version is unclear, but since the sample used the one that returns a value, it is recommended to use that one)
     */
    func contextMenuDidDeselect(_ contextMenu: ContextMenu,
                                cell: ContextMenuCell,
                                targetedView: UIView,
                                didSelect item: ContextMenuItem,
                                forRowAt index: Int) {
    }
    
    /**
     Called when the context menu appears
     */
    func contextMenuDidAppear(_ contextMenu: ContextMenu) {
        print("Context menu appeared!")
    }
    
    /**
     Called when the context menu disappears
     */
    func contextMenuDidDisappear(_ contextMenu: ContextMenu) {
        print("Context menu disappeared!")
    }
    
    
}

Create a function for long-press

Next, let's create the content for the context menu. We'll add long-press detection to the cell and call the context menu when it's triggered.

Create the following function and include the logic to be executed upon long-press inside it:

HogeTableViewController.swift
/// Method called when a cell is long-pressed
@objc func cellLongPressed(_ recognizer: UILongPressGestureRecognizer) {

    // Get the cell's Path at the pressed location
    let point = recognizer.location(in: tableView)
    // The indexPath corresponding to the pressed location
    let indexPath = tableView.indexPathForRow(at: point)
        
    if indexPath == nil {  // If there is no indexPath
            
        return  // Return immediately and do not process further
            
    } else if recognizer.state == UIGestureRecognizer.State.began  {
        // Processing when long-pressed
            
        // Create the content of the context menu
        let edit = ContextMenuItemWithImage(title: "Edit", image: UIImage(systemName: "square.and.pencil")!)
        let delete = ContextMenuItemWithImage(title: "Delete", image: UIImage(systemName: "trash")!)
            
	 // Determine the items to display in the context menu
        CM.items = [edit, delete]
	// Show the menu
        CM.showMenu(viewTargeted: tableView.cellForRow(at: indexPath!)!,
                    delegate: self,
                    animated: true)
            
    }
}

Connect the recognizer to the tableView

Next, add this to the tableView in viewDidLoad().

HogeTableViewController.swift
override func viewDidLoad() {
    super.viewDidLoad()
	
    // ~Other processes~
    
    // Long-press detection
    // Declare UILongPressGestureRecognizer
    let longPressRecognizer = UILongPressGestureRecognizer(target: self,
                                                           action: #selector(HogeTableViewController.cellLongPressed(_ :)))

    // Don't forget to set the `UIGestureRecognizerDelegate`
    longPressRecognizer.delegate = self

    // Set the recognizer to the tableView
    tableView.addGestureRecognizer(longPressRecognizer)
    
}

Reconfiguring the extension

Now the context menu should appear when a cell is long-pressed. However, currently, it only displays and doesn't execute anything, so we will edit the extension we added at the beginning again.

HogeTableViewController.swift

// Overriding the function within HogeTableViewController: ContextMenuDelegate

/**
    Executed when a context menu option is selected
    - Parameters:
        - contextMenu: Presumably the context menu itself
        - cell: The cell **of the selected context menu**
        - targetedView: The source view of the context menu
        - item: The selected context item (contains title, image, etc.)
        - index: The coordinates **of the selected context item**
 */
func contextMenuDidSelect(_ contextMenu: ContextMenu,
                          cell: ContextMenuCell,
                          targetedView: UIView,
                          didSelect item: ContextMenuItem,
                          forRowAt index: Int) -> Bool {
	// You can load the long-pressed cell by re-specifying the type
	let pressedTableCell = targetedView as! HogeTableViewCell
	
	// If you want to get information within the cell
	let someImage: UIImage = pressedTableCell.someImageView.image
	let hugaTitle: String = pressedTableCell.hugaLabel.text
	// You can retrieve it like this
	
	// Selected context menu item => item
	print("Selected menu title: ", item.title)
	
	
	// If you want to branch conditions based on the index of the selected menu
	switch index {
	case 0:
	    // 0th cell (executed when the top menu is tapped)
	    // In this example, it is set to the Edit menu
	    print("Edit was pressed!")
	
	case 1:
	    // Same logic here
	    print("Delete was pressed!")
	
	default:
	    // Executed when other cells are tapped
	    break
	}
	
	// Finally, return a boolean value
	return true
	
}

// There are also three functions below this

Since contextMenuDidSelect() is called when a context menu is selected, please use this example as a reference for your implementation.

Conclusion

I personally found it very easy to use, but since there weren't any introductory articles in Japanese, I decided to write this in hopes it would help anyone trying to achieve something similar. If there are any mistakes, please let me know.

GitHubで編集を提案

Discussion