Bird
Raised Fist0
iOS Swiftmobile~15 mins

Swipe actions in iOS Swift - Deep Dive

Choose your learning style10 modes available
Overview - Swipe actions
What is it?
Swipe actions let users quickly interact with items in a list by swiping left or right on them. For example, swiping a message to delete or mark it as read. This gesture reveals buttons or options related to that item without opening a new screen. It makes apps feel faster and easier to use.
Why it matters
Without swipe actions, users would need to tap multiple times or open menus to do simple tasks like deleting or archiving. Swipe actions save time and reduce frustration by putting common commands right under the user's finger. They improve app usability and make the experience more natural and efficient.
Where it fits
Before learning swipe actions, you should understand how to create lists using UITableView or UICollectionView in iOS. After mastering swipe actions, you can explore more advanced gestures, custom animations, and accessibility features to make your app even friendlier.
Mental Model
Core Idea
Swipe actions are quick shortcuts hidden behind a swipe gesture on list items that reveal buttons for common tasks.
Think of it like...
It's like sliding a drawer open on a desk to quickly grab a tool without standing up or searching around.
List Item
┌─────────────────────────────┐
│ Item Content                │
│                             │
│ <--- Swipe Left or Right --->│
│                             │
│ [Delete] [Archive] Buttons  │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding basic list setup
🤔
Concept: Learn how to create a simple list using UITableView in Swift.
Create a UITableView and implement UITableViewDataSource methods to show rows with text labels. This is the foundation for adding swipe actions later.
Result
A scrollable list of items appears on screen.
Knowing how to build a list is essential because swipe actions attach to each list item.
2
FoundationRecognizing user gestures on list items
🤔
Concept: Understand how iOS detects swipe gestures on table view cells.
iOS automatically detects horizontal swipes on UITableViewCells and can trigger delegate methods to show actions.
Result
Swiping left or right on a list item triggers system callbacks.
Realizing that swipe detection is built-in helps you focus on what happens after the swipe.
3
IntermediateImplementing trailing swipe actions
🤔Before reading on: do you think trailing swipe actions appear when swiping left or right? Commit to your answer.
Concept: Add buttons that appear when the user swipes left on a list item (trailing swipe).
Use UITableViewDelegate method tableView(_:trailingSwipeActionsConfigurationForRowAt:) to provide UIContextualAction buttons like Delete or Archive.
Result
Swiping left on a row reveals buttons on the right side for quick actions.
Knowing trailing swipe actions are the most common lets you prioritize implementing them first.
4
IntermediateAdding leading swipe actions
🤔Before reading on: do you think leading swipe actions appear when swiping left or right? Commit to your answer.
Concept: Add buttons that appear when the user swipes right on a list item (leading swipe).
Implement tableView(_:leadingSwipeActionsConfigurationForRowAt:) to show buttons like Mark as Read or Flag when swiping right.
Result
Swiping right on a row reveals buttons on the left side for quick actions.
Understanding leading swipe actions expands your app's interaction options and matches user expectations.
5
IntermediateCustomizing swipe action appearance
🤔
Concept: Change colors, icons, and behavior of swipe buttons to match your app style.
Set properties on UIContextualAction like backgroundColor and image to customize the look. You can also control whether the action performs a full swipe to trigger automatically.
Result
Swipe buttons look unique and fit your app's design.
Customizing appearance improves user experience by making actions clear and visually consistent.
6
AdvancedHandling swipe action completion and side effects
🤔Before reading on: do you think swipe actions automatically delete items or do you need to update data manually? Commit to your answer.
Concept: Manage what happens after a swipe action is tapped, like updating data and UI.
In the action handler closure, update your data source (e.g., remove an item) and call tableView.deleteRows(at:) to animate removal. Then call completion(true) to close the swipe.
Result
The list updates smoothly after an action, reflecting the user's choice.
Knowing you must manually update data prevents bugs where UI and data get out of sync.
7
ExpertSupporting accessibility and custom gestures
🤔Before reading on: do you think swipe actions are automatically accessible to all users? Commit to your answer.
Concept: Make swipe actions usable by everyone, including those using VoiceOver or alternative input methods.
Provide accessibility labels and hints for actions. Consider adding buttons elsewhere for users who cannot swipe. Also, handle gesture conflicts with other interactions gracefully.
Result
All users can access swipe actions, improving app inclusivity and compliance.
Understanding accessibility ensures your app reaches a wider audience and avoids legal issues.
Under the Hood
When a user swipes on a UITableViewCell, iOS detects the gesture and calls delegate methods to ask for action configurations. These configurations create UIContextualAction objects that the system displays as buttons. The system manages the animation and gesture tracking. When a button is tapped, the handler closure runs, where you update your data and UI. The swipe actions are part of the UITableView's internal gesture recognizers and view hierarchy.
Why designed this way?
Apple designed swipe actions to be easy to implement and consistent across apps, improving user familiarity. By using delegate methods and UIContextualAction, developers can customize behavior without rewriting gesture handling. This separation keeps code clean and leverages system optimizations for smooth animations and accessibility.
User Swipe Gesture
      ↓
┌─────────────────────────────┐
│ UITableView detects swipe   │
│                             │
│ Calls delegate methods      │
│                             │
│ Creates UIContextualActions │
│                             │
│ Displays buttons on cell    │
│                             │
│ User taps button → handler  │
│                             │
│ Update data and UI          │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do swipe actions automatically delete the item from your data source? Commit yes or no.
Common Belief:Swipe actions automatically handle deleting or modifying data when tapped.
Tap to reveal reality
Reality:Swipe actions only show buttons and call your handler; you must update your data and UI manually.
Why it matters:If you assume automatic data changes, your app's UI and data will get out of sync, causing crashes or wrong displays.
Quick: Can you add swipe actions to any UIView, not just table cells? Commit yes or no.
Common Belief:Swipe actions can be added to any view by detecting gestures manually.
Tap to reveal reality
Reality:UIKit provides built-in swipe actions only for UITableView and UICollectionView cells; other views require custom gesture handling.
Why it matters:Trying to add swipe actions to unsupported views without custom code wastes time and leads to inconsistent behavior.
Quick: Do swipe actions always appear on both left and right sides by default? Commit yes or no.
Common Belief:Swipe actions appear on both sides automatically without extra code.
Tap to reveal reality
Reality:You must implement separate delegate methods for leading (right swipe) and trailing (left swipe) actions explicitly.
Why it matters:Assuming automatic appearance causes confusion when one side has no actions, leading to poor user experience.
Quick: Are swipe actions fully accessible to VoiceOver users without extra work? Commit yes or no.
Common Belief:Swipe actions are automatically accessible to all users including those using VoiceOver.
Tap to reveal reality
Reality:You must provide accessibility labels and consider alternative controls for users who cannot perform swipe gestures.
Why it matters:Ignoring accessibility excludes users with disabilities and can violate app store guidelines.
Expert Zone
1
Swipe actions can be combined with custom animations to create unique user experiences beyond default behavior.
2
Full swipe gestures can trigger actions automatically, but misuse can cause accidental deletions; careful UX design is needed.
3
Handling gesture conflicts between swipe actions and other gestures (like pan or drag) requires deep understanding of gesture recognizer priorities.
When NOT to use
Avoid swipe actions when your list items have complex interactions or multiple nested gestures that conflict. Instead, use explicit buttons or context menus. Also, for accessibility-critical apps, provide alternative controls alongside swipe actions.
Production Patterns
In real apps, swipe actions are often combined with undo features to prevent accidental data loss. Developers also customize action colors and icons to match branding. Some apps use swipe actions only on certain rows or dynamically enable/disable them based on item state.
Connections
Context Menus
Builds-on
Swipe actions are a quick-access subset of context menus, which provide more options on long press or right click.
Gesture Recognizers
Same pattern
Swipe actions rely on gesture recognizers to detect user swipes, showing how gestures enable rich interactions.
Human-Computer Interaction (HCI)
Builds-on
Understanding swipe actions deepens knowledge of HCI principles like affordance and direct manipulation.
Common Pitfalls
#1Swipe action buttons do not appear when swiping.
Wrong approach:func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { return nil }
Correct approach:func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let delete = UIContextualAction(style: .destructive, title: "Delete") { _, _, completion in // handle delete completion(true) } return UISwipeActionsConfiguration(actions: [delete]) }
Root cause:Returning nil means no actions are provided, so no buttons show up.
#2Deleting an item visually but not updating data source.
Wrong approach:In swipe action handler: tableView.deleteRows(at: [indexPath], with: .automatic) // No data source update
Correct approach:Remove item from data array first, then call tableView.deleteRows(at: [indexPath], with: .automatic)
Root cause:UI updates must match data changes; otherwise, app crashes or shows inconsistent state.
#3Using swipe actions without accessibility labels.
Wrong approach:let action = UIContextualAction(style: .normal, title: "Flag") { _, _, completion in completion(true) }
Correct approach:let action = UIContextualAction(style: .normal, title: "Flag") { _, _, completion in completion(true) } action.accessibilityLabel = "Flag this message"
Root cause:Without accessibility labels, screen readers cannot describe the action to users.
Key Takeaways
Swipe actions provide fast, intuitive shortcuts for list item tasks by revealing buttons on swipe gestures.
They require implementing specific delegate methods and manually updating your data and UI after actions.
Customizing appearance and handling accessibility are essential for a polished, inclusive user experience.
Understanding the underlying gesture detection and action handling helps avoid common bugs and UX issues.
Swipe actions fit naturally into iOS lists and improve app usability when used thoughtfully and carefully.

Practice

(1/5)
1. What is the main purpose of using UIContextualAction in a swipe action on iOS?
easy
A. To handle tap gestures on the entire screen
B. To create buttons that appear when the user swipes a table cell
C. To change the background color of the app
D. To add animations to buttons outside of swipe actions

Solution

  1. Step 1: Understand swipe actions in iOS

    Swipe actions allow users to reveal buttons by swiping on a list item.
  2. Step 2: Role of UIContextualAction

    UIContextualAction creates the buttons shown during the swipe gesture.
  3. Final Answer:

    To create buttons that appear when the user swipes a table cell -> Option B
  4. Quick Check:

    UIContextualAction = Swipe buttons [OK]
Hint: UIContextualAction = swipe buttons on list items [OK]
Common Mistakes:
  • Confusing swipe action buttons with general tap gestures
  • Thinking UIContextualAction changes app colors
  • Assuming it adds animations unrelated to swipe
2. Which of the following is the correct way to create a UIContextualAction for a swipe action in Swift?
easy
A. let action = UIContextualAction(style: .normal, title: "Delete", handler: { _, _, completionHandler in completionHandler(true) })
B. let action = UIContextualAction(style: "normal", title: "Delete", handler: { _, _, completionHandler in completionHandler(true) })
C. let action = UIContextualAction(style: .normal, title: Delete, handler: { _, _, completionHandler in completionHandler(true) })
D. let action = UIContextualAction(style: .normal, title: "Delete")

Solution

  1. Step 1: Check UIContextualAction initializer syntax

    The initializer requires a style enum, a String title, and a handler closure with parameters.
  2. Step 2: Validate each option

    let action = UIContextualAction(style: .normal, title: "Delete", handler: { _, _, completionHandler in completionHandler(true) }) uses correct enum style, quotes around title, and proper handler closure with completion call.
  3. Final Answer:

    let action = UIContextualAction(style: .normal, title: "Delete", handler: { _, _, completionHandler in completionHandler(true) }) -> Option A
  4. Quick Check:

    Correct initializer syntax = let action = UIContextualAction(style: .normal, title: "Delete", handler: { _, _, completionHandler in completionHandler(true) }) [OK]
Hint: Use .normal enum and quoted title with handler closure [OK]
Common Mistakes:
  • Using string instead of enum for style
  • Missing quotes around title string
  • Omitting handler closure or completion call
3. Given this code snippet inside a UITableViewDelegate method, what happens when the user swipes the cell?
let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in
    print("Deleted")
    completionHandler(true)
}
let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
return configuration
medium
A. A red "Delete" button appears; tapping it prints "Deleted" and closes swipe
B. The cell immediately deletes without user interaction
C. Nothing happens because completionHandler is not called
D. The swipe gesture is disabled

Solution

  1. Step 1: Analyze swipe action setup

    A destructive style button labeled "Delete" is created with a handler that prints and calls completionHandler(true).
  2. Step 2: Understand user interaction

    Swiping reveals the button; tapping it triggers the handler, printing "Deleted" and ending the swipe.
  3. Final Answer:

    A red "Delete" button appears; tapping it prints "Deleted" and closes swipe -> Option A
  4. Quick Check:

    Swipe button tap triggers handler = A red "Delete" button appears; tapping it prints "Deleted" and closes swipe [OK]
Hint: Completion handler true ends swipe and triggers action [OK]
Common Mistakes:
  • Thinking swipe deletes immediately without tap
  • Forgetting to call completionHandler(true)
  • Assuming swipe gesture disables without code
4. Identify the error in this swipe action handler code:
let editAction = UIContextualAction(style: .normal, title: "Edit") { action, view, _ in
    print("Edit tapped")
}
medium
A. Title string should be lowercase
B. Incorrect style enum used for edit action
C. Missing call to completionHandler inside the closure
D. Closure parameters are in wrong order

Solution

  1. Step 1: Review UIContextualAction handler requirements

    The handler closure must call the completionHandler to signal action completion.
  2. Step 2: Check the given code

    The closure ignores the third parameter (completionHandler) and does not call it, causing swipe to hang.
  3. Final Answer:

    Missing call to completionHandler inside the closure -> Option C
  4. Quick Check:

    Always call completionHandler in swipe action handler [OK]
Hint: Always call completionHandler(true/false) in handler closure [OK]
Common Mistakes:
  • Ignoring completionHandler call
  • Using wrong style enum (normal is valid here)
  • Thinking title case matters
  • Mixing closure parameter order
5. You want to add two swipe actions: "Flag" (normal style) and "Delete" (destructive style) to a table cell. Which code correctly creates and returns the swipe configuration?
hard
A. let flag = UIContextualAction(style: .normal, title: "Flag") { _, _, completion in completion(true) } let delete = UIContextualAction(style: .destructive, title: "Delete") { _, _, completion in completion(true) } return UISwipeActionsConfiguration(actions: [flag, delete])
B. let flag = UIContextualAction(style: .normal, title: "Flag") { _, _, completionHandler in completionHandler(true) } let delete = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in completionHandler(true) } return UISwipeActionsConfiguration(actions: [flag, delete])
C. let flag = UIContextualAction(style: .normal, title: "Flag") { _, _, completionHandler in completionHandler(false) } let delete = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in completionHandler(true) } return UISwipeActionsConfiguration(actions: [flag, delete])
D. let flag = UIContextualAction(style: .normal, title: "Flag") { _, _, completionHandler in completionHandler(true) } let delete = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in completionHandler(true) } return UISwipeActionsConfiguration(actions: [delete, flag])

Solution

  1. Step 1: Confirm action creation and completion calls

    Both actions use correct styles and call completionHandler(true) to indicate success.
  2. Step 2: Check order of actions in configuration

    Swipe actions appear in order given; "Delete" usually placed first for prominence, then "Flag".
  3. Final Answer:

    Actions created with correct styles and completion calls; configuration returns [delete, flag] -> Option D
  4. Quick Check:

    Correct styles, completion calls, and order = let flag = UIContextualAction(style: .normal, title: "Flag") { _, _, completionHandler in completionHandler(true) } let delete = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in completionHandler(true) } return UISwipeActionsConfiguration(actions: [delete, flag]) [OK]
Hint: Call completionHandler(true) and order destructive before normal [OK]
Common Mistakes:
  • Calling completionHandler(false) which cancels action
  • Using wrong variable name for completionHandler
  • Incorrect order of actions in array
  • Omitting completionHandler call
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard