UIControl
UIControl represents a control: a view that receives touches and turns the course of a touch into a set of "control events" that it fires. It is the common parent class of all interactive controls: UIButton (button), UITextField (text field), UISwitch (switch), and UISlider (slider) all inherit from it.
A control provides two things:
- States: normal, finger held down, disabled, selected. Subclasses show a different appearance for each state.
- Control events: 16 events such as finger down, finger moved out, and finger lifted, listened to with
addEventListener().
UIControl can also be created directly. A control created directly displays nothing; use it as a custom tappable area: give it a background color, add text and icons to it, then listen to its events. A plain UIView does not fire control events; to make a plain view respond to taps, use a gesture recognizer.
Inheritance: EventTarget → NSObject → UIResponder → UIView → UIControl
For how to build a tappable area with control events and handle press and release, see the guide Handling touches on controls.
Constructor
Creates a control that displays nothing, for use as a custom tappable area.
Instance properties
Also inherits the properties of UIView. Inherited properties commonly used on controls are backgroundColor, alpha, layer, and isUserInteractionEnabled.
| Property | Description |
|---|---|
isEnabled | Whether the control receives touches. When false, the control enters the disabled state |
isSelected | Whether the control is in the selected state. Only the app's code changes it |
isHighlighted | Whether the control is in the highlighted state. The system sets it to true while a finger is held down |
state read-only | All current states, as an array of state names |
isTracking read-only | Whether the control is tracking a touch |
isTouchInside read-only | Whether the touch being tracked is currently within the control's bounds |
contentHorizontalAlignment | Horizontal position of the content a subclass displays within the control |
contentVerticalAlignment | Vertical position of the content a subclass displays within the control |
Instance methods
Also inherits the methods of UIView, and dispatchEvent() from EventTarget.
| Method | Description |
|---|---|
addEventListener() | Listens for a control event |
removeEventListener() | Removes a listener |
sendActionsForControlEvents() | Makes the control fire the given events, through the same path as a real touch |
Events
There are 16 control events in total, listened to with addEventListener(). Names are case-sensitive. An event is fired only on the control the listener is registered on; it does not bubble and cannot be canceled.
Touch events: fired by all controls. The table below lists them in the order of a touch. The event object carries the touch location.
| Event | When it fires |
|---|---|
touchdown | A finger presses down on the control |
touchdownrepeat | On repeated taps in quick succession, from the second press on |
touchdraginside | A finger held down moves within the control's bounds |
touchdragexit | The moment a finger held down moves from inside the control to outside it |
touchdragoutside | A finger held down moves outside the control's bounds |
touchdragenter | The moment a finger held down moves from outside the control back inside it |
touchupinside | A finger is lifted within the control's bounds |
touchupoutside | A finger is lifted outside the control's bounds |
touchcancel | The system canceled the touch; the finger was not lifted normally |
A touch ends with exactly one of touchupinside, touchupoutside, or touchcancel.
Other events: fired only by specific subclasses. The event object does not carry the touch location.
| Event | When it fires |
|---|---|
click | The user completed the control's primary action. For a button, that is a tap |
change | The user changed the control's value. Fired by controls that have a value, such as switches and sliders |
menuaction | Before the control shows a menu |
focus | A text field begins editing |
input | The user changed a text field's text |
blur | A text field ends editing |
return | The user pressed the Return key on the keyboard |
traitchange, which every view has, can also be listened to on a control. Text fields have five additional cancelable events; see UITextField.
Listening for any other name does not throw: it is treated as a custom event and fires only when you dispatch it yourself with dispatchEvent(). Names starting with @ are reserved for the runtime; listening for them throws TypeError.
States
At any moment a control is in one or more states. Subclasses show a different appearance for each state; for example, a button can have different text for each state.
| State | When the control is in this state | Who changes it |
|---|---|---|
normal | None of the four below applies | Nobody |
highlighted | isHighlighted is true: a finger is pressed on the control | The system, automatically. Set to true on press and back to false on release. The app's code can also write it |
disabled | isEnabled is false | The app's code |
selected | isSelected is true | The app's code. The system never changes it automatically |
focused | The control has focus. Not verified in the simulator. | The system |
States other than normal can hold at the same time, for example "selected and disabled". That is why state reads as an array.
State changes do not fire events. isEnabled and isSelected are changed only by the app's code, so no notification is needed. isHighlighted is changed by the system during a touch; use touchdown and the three ending events to learn when a touch starts and ends.
Touch location
For the nine events whose names start with touch, the event object's type is UIControlTouchEvent, which has two more read-only fields than a plain Event:
| Field | Type | Meaning |
|---|---|---|
location | CGPoint or null | The finger's position, in this control's own coordinate system, in pt. null when there is no real touch |
tapCount | number | The number of consecutive taps, counted in taps. 0 when there is no real touch |
- The callback parameter is declared as
Event. To read these two fields, cast it with/** @type {UIControlTouchEvent} */ (e). - Events fired by
sendActionsForControlEvents()have no corresponding touch:locationisnullandtapCountis 0.nulldiffers from(0, 0):(0, 0)is the control's top-left corner, a real position. - These two values can only be read from the event object. By the time the callback runs, the touch may already have ended, and the control does not store the touch position. To convert the position to another view's coordinate system, use
convertPoint()onUIView. - The objects of the other seven events do not have these two fields; reading them gives
undefined, and'location' in eisfalse.focus,input,blur, andreturnare text input events and have nothing to do with touch points;change,click, andmenuactiondo not necessarily come from a touch, since code callingsendActionsForControlEvents()also fires them.
When callbacks run
Callbacks do not run immediately when a touch happens. They are queued to run after the current round of code; for background, see How the runtime works.
This has two consequences:
- A callback sees the state at the moment it runs, not at the moment the event happened. Reading
isHighlightedin atouchdowncallback givestruewhile the finger is held down; if the finger is lifted quickly after pressing, it may givefalse, because the system has already set it back by the time the callback runs (measured). The event object does not carry the control's state at the moment of the event, only the touch location. - The order of control events and timer callbacks is not guaranteed. If you set a 0 ms timer right after
sendActionsForControlEvents(), the timer callback may run first (measured). When you need to wait for an event, continue the follow-up work inside the event callback.
An exception thrown in a callback does not affect the control. The exception fires error on application; if no listener cancels it, the console prints a log starting with Uncaught. Other callbacks for the same event still run, and the control keeps firing events afterward.
Examples
Building your own tappable area
Starting from a blank app, place a green tappable area in the center of the screen. It fades while held down, and each tap adds one to a count.
application.addEventListener('sceneconnect', (e) => {
const win = new UIWindow(e.scene);
const page = new UIViewController();
page.view.backgroundColor = 'systemBackground';
win.rootViewController = page;
win.makeKeyAndVisible();
const card = new UIControl();
card.backgroundColor = 'systemGreen';
card.layer.cornerRadius = 10;
const label = new UILabel();
label.text = 'Taps: 0';
label.textColor = 'white';
label.isUserInteractionEnabled = false;
card.addSubview(label);
card.addEventListener('touchdown', () => {
card.alpha = 0.6;
});
let count = 0;
card.addEventListener('touchupinside', () => {
card.alpha = 1;
count += 1;
label.text = 'Taps: ' + count;
console.log('Tap', count);
});
card.addEventListener('touchupoutside', () => {
card.alpha = 1;
});
card.addEventListener('touchcancel', () => {
card.alpha = 1;
});
card.translatesAutoresizingMaskIntoConstraints = false;
label.translatesAutoresizingMaskIntoConstraints = false;
page.view.addSubview(card);
NSLayoutConstraint.activateConstraints([
card.centerXAnchor.constraintEqualToAnchor(page.view.centerXAnchor),
card.centerYAnchor.constraintEqualToAnchor(page.view.centerYAnchor),
card.widthAnchor.constraintEqualToConstant(220),
card.heightAnchor.constraintEqualToConstant(52),
label.centerXAnchor.constraintEqualToAnchor(card.centerXAnchor),
label.centerYAnchor.constraintEqualToAnchor(card.centerYAnchor),
]);
});Effect
- A green rounded rectangle 220 pt wide and 52 pt tall appears in the center of the screen, with white "Taps: 0" in the middle.
- The rectangle fades while a finger is held on it and recovers on release.
- When the finger is lifted on the rectangle, the text changes to "Taps: 1" and the console prints
Tap 1. - When the finger presses, slides outside the rectangle, and is then lifted, the text does not change and the console prints nothing.
This code has not been run as a whole in the simulator. Creating a UIControl, its background color, corner radius, constraints, touchdown, and touchupinside have run in the acceptance tests, and on a real tap these two events fire in that order. Firing of touchupoutside and touchcancel, and card receiving a touch that lands on the text, are not verified in the simulator.
Reading the current state
const control = new UIControl();
console.log(control.state.join(', '));
control.isSelected = true;
control.isEnabled = false;
console.log(control.state.includes('selected'), control.state.includes('disabled'));Result: prints normal first, then true true. When none of the three states holds, the array has the single item 'normal'; when the control is both selected and disabled, it has two items, in no guaranteed order.
For more patterns, see the guide Handling touches on controls.
Corresponding iOS API
| ObjC | JS |
|---|---|
[[UIControl alloc] init] | new UIControl() |
[c addTarget:self action:@selector(tap:) forControlEvents:UIControlEventTouchUpInside] | c.addEventListener('touchupinside', fn) |
[c removeTarget:self action:@selector(tap:) forControlEvents:UIControlEventTouchUpInside] | c.removeEventListener('touchupinside', fn) |
[c sendActionsForControlEvents:UIControlEventTouchDown | UIControlEventTouchUpInside] | c.sendActionsForControlEvents(['touchdown', 'touchupinside']) |
c.enabled = NO | c.isEnabled = false |
c.selected = YES | c.isSelected = true |
c.highlighted | c.isHighlighted |
c.state & UIControlStateSelected | c.state.includes('selected') |
c.tracking | c.isTracking |
c.touchInside | c.isTouchInside |
c.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeading | c.contentHorizontalAlignment = 'leading' |
c.contentVerticalAlignment = UIControlContentVerticalAlignmentTop | c.contentVerticalAlignment = 'top' |
Event name mapping:
| ObjC | JS |
|---|---|
UIControlEventTouchDown and the other eight touch events | The name without the UIControlEvent prefix, all lowercase: 'touchdown', 'touchupinside', … |
UIControlEventPrimaryActionTriggered | 'click' |
UIControlEventValueChanged | 'change' |
UIControlEventMenuActionTriggered | 'menuaction' |
UIControlEventEditingDidBegin | 'focus' |
UIControlEventEditingChanged | 'input' |
UIControlEventEditingDidEnd | 'blur' |
UIControlEventEditingDidEndOnExit | 'return' |
- State names are the ObjC constants without the
UIControlStateprefix, with the first letter lowercase. The native bitmask is an array of strings in JS. - The native
addTarget:action:forControlEvents:is called target-action: you register an object and one of its methods with the control, and the control calls that method when the event happens. In JS, useaddEventListener()instead.
Mapping to browser events
This table is only for looking up correspondences, for people familiar with browser events.
| Browser | Control event |
|---|---|
pointerdown | touchdown |
pointermove | touchdraginside, touchdragoutside, touchdragenter, touchdragexit |
pointerup | touchupinside, touchupoutside |
pointercancel | touchcancel |
click | click (buttons), touchupinside (a UIControl created directly) |
input, focus, blur | Same names, same meaning |
clientX, clientY | location on events starting with touch, in the control's own coordinate system |
element.disabled = true | control.isEnabled = false |
See also
- Handling touches on controls: tappable areas, appearance while pressed, simulated taps, disabling
UIButton: the most common control, with text and icons set per stateUITextField: text field; firesfocus,input,blur, andreturnUISwitch,UISlider,UIStepper,UISegmentedControl,UIPageControl,UIDatePicker: controls that firechangeUIView: the parent class; position, size, background color,isUserInteractionEnabled- Gesture recognizers: make views that are not controls respond to taps and long presses
- Native classes:
UIControlcannot be subclassed, and what to write instead