Skip to content

UITraitChangeEvent ​

UITraitChangeEvent represents a change in the set of values describing the UI's environment, such as dark mode being turned on or off, or the text size setting.

The traitchange event of UIView, UIViewController, and UIWindowScene is this class. The set of values is a UITraitCollection. The event carries the set from before the change; read the current one from event.target.traitCollection.

Inheritance: Event → UITraitChangeEvent

Constructor ​

UITraitChangeEvent()

Creates a UITraitChangeEvent. The runtime creates one itself when it fires the events below; app code can use it to build an event object and fire it with dispatchEvent() to try out a listener.

Instance properties ​

Also inherits the properties of Event; the most commonly used are type and target. The properties below are read-only; assigning to them throws TypeError.

PropertyDescription
previousTraitCollection read-onlyThe set of values before the change

These properties live on the prototype, not on the event object itself: Object.keys(event) and { ...event } don't include them, so read them one by one. See Events with fields.

Events that use this class ​

ObjectEvents
UIView and its subclassestraitchange
UIViewController and its subclassestraitchange
UIWindowScenetraitchange

It can't be canceled: cancelable is false, and preventDefault() has no effect.

Examples ​

js
const page = new UIViewController();
page.addEventListener('traitchange', (e) => {
  console.log(e instanceof UITraitChangeEvent, e.previousTraitCollection.userInterfaceStyle);
});

Effect: when the page's traits change, prints true and the style from before the change.

Corresponding iOS API ​

ObjCJS
[view registerForTraitChanges:… withHandler:^(id env, UITraitCollection *previous) { … }]view.addEventListener('traitchange', fn)
previousCollectionevent.previousTraitCollection

See also ​