Attach parameter to button.addTarget action in Swift
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
UIButton.addTarget(_:action:for:) uses the target-action pattern to invoke a method when a button event occurs. The action parameter is a Selector — a reference to an Objective-C method signature — which limits you to specific parameter patterns. You cannot directly pass arbitrary custom parameters through addTarget. This article covers several workarounds to associate custom data with button actions.
Basic addTarget Usage
The selector can accept zero parameters, one parameter (sender), or two parameters (sender and event):
Method 1: Using the tag Property
The simplest way to pass an integer identifier:
Limitation: tag is only an Int. For complex data, use other methods.
Method 2: Subclassing UIButton
Create a custom button class that holds additional properties:
Method 3: Using Associated Objects
Attach arbitrary data to any UIButton without subclassing:
Method 4: Closure-Based Actions (iOS 14+)
Starting with iOS 14, use UIAction with closures to capture any variables:
Or add the action after creation:
This is the most modern and clean approach.
Method 5: Using a Dictionary for Mapping
Map buttons to their data through a dictionary:
In UITableView/UICollectionView Cells
For buttons inside cells, use closures or delegate patterns:
Common Pitfalls
- Retain cycles: When using closures (UIAction) that capture
self, always use[weak self]to avoid retain cycles that prevent the view controller from being deallocated. - Cell reuse with tag: In
UITableView, cells are reused. If you usebutton.tag = indexPath.row, the tag becomes stale after insertions/deletions. Prefer closure-based approaches for cells. - Selector string typos: Using
#selectorprovides compile-time checking. Never useSelector("methodName")strings — they crash at runtime if misspelled. - @objc requirement: Methods referenced by
#selectormust be marked@objc, which requires the class to inherit fromNSObject(or be marked@objcMembers). - Multiple actions:
addTargetcan attach multiple actions to the same button. Calling it twice with different selectors registers both — they all fire on tap. UseremoveTargetfirst if replacing an action.
Summary
addTargetdoes not support arbitrary parameters — only the sender and event- Use
button.tagfor simple integer identifiers - Subclass
UIButtonor use associated objects for complex data - Use
UIActionclosures (iOS 14+) for the cleanest approach with captured variables - In table/collection view cells, use closure callbacks to avoid stale tag values
Related reading
- Attempt to insert non-property list object when trying to save a custom object in Swift 3
- Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy
- Attempt to set a non-property-list object as an NSUserDefaults
- Attempting to load the view of a view controller while it is deallocating... UISearchController
- Attempting to load the view of a view controller while it is deallocating... UISearchController
- Attributed string with custom fonts in storyboard does not load correctly
- Auto-fit TextView for Android
- Auto-layout What creates constraints named UIView-Encapsulated-Layout-Width Height?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.