1.4 MiB
https://developer.apple.com/documentation/uikit/
Framework
UIKit
Construct and manage a graphical, event-driven user interface for your iOS, iPadOS, or tvOS app.
Overview
UIKit provides a variety of features for building apps, including components you can use to construct the core infrastructure of your iOS, iPadOS, or tvOS apps. The framework provides the window and view architecture for implementing your UI, the event-handling infrastructure for delivering Multi-Touch and other types of input to your app, and the main run loop for managing interactions between the user, the system, and your app.
UIKit also includes support for animations, documents, drawing and printing, text management and display, search, app extensions, resource management, and getting information about the current device. You can also customize accessibility support, and localize your app’s interface for different languages, countries, or cultural regions.
UIKit works seamlessly with the SwiftUI framework, so you can implement parts of your UIKit app in SwiftUI or mix interface elements between the two frameworks. For example, you can place UIKit views and view controllers inside SwiftUI views, and vice versa.
To build a macOS app, you can use SwiftUI to create an app that works across all of Apple’s platforms, or use AppKit to create an app for Mac only. Alternatively, you can bring your UIKit iPad app to the Mac with Mac Catalyst.
Topics
Essentials
Adopting Liquid Glass
Find out how to bring the new material to your app.
UIKit updates
Learn about important changes to UIKit.
About App Development with UIKit
Learn about the basic support that UIKit and Xcode provide for your iOS and tvOS apps.
Secure personal data, and respect user preferences for how data is used.
App structure
UIKit manages your app’s interactions with the system and provides classes for you to manage your app’s data and resources.
Manage life-cycle events and your app’s UI scenes, and get information about traits and the environment in which your app runs.
Organize your app’s data and share that data on the pasteboard.
Manage the images, strings, storyboards, and nib files that you use to implement your app’s interface.
Extend your app’s basic functionality to other parts of the system.
Display activity-based services to people.
Create a version of your iPad app that users can run on a Mac device.
User interface
Views help you display content onscreen and facilitate user interactions; view controllers help you manage views and the structure of your interface.
Present your content onscreen and define the interactions allowed with that content.
Manage your interface using view controllers and facilitate navigation around your app’s content.
Use stack views to lay out the views of your interface automatically. Use Auto Layout when you require precise placement of your views.
Apply Liquid Glass to views, support Dark Mode in your app, customize the appearance of bars, and use appearance proxies to modify your UI.
Provide feed
Responders and gesture recognizers help you handle touches and other events. Drag and drop, focus, peek and pop, and accessibility handle other user interactions.
Encapsulate your app’s event-handling logic in gesture recognizers so that you can reuse that code throughout your app.
Simplify interactions with your app using menu systems, contextual menus, Home Screen quick actions, and keyboard shortcuts.
Bring drag and drop to your app by using interaction APIs with your views.
Support pointer interactions in your custom controls and views.
Handle user interactions like double tap and squeeze on Apple Pencil.
Navigate the interface of your UIKit app using a remote, game controller, or keyboard.
Make your UIKit apps accessible to everyone who uses iOS and tvOS.
Graphics, drawing, and printing
UIKit provides classes and protocols that help you configure your drawing environment and render your content.
Create and manage images, including those that use bitmap and PDF formats.
Configure your app’s drawing environment using colors, renderers, draw paths, strings, and shadows.
Display the system print panels and manage the printing process.
Text
In addition to text views that simplify displaying text in your app, UIKit provides custom text management and rendering that supports the system keyboards.
Display text, manage fonts, and check spelling.
Manage text storage and perform custom layout of text-based content in your app’s views.
Configure the system keyboard, create your own keyboards to handle input, or detect key presses on a physical keyboard.
Add support for Writing Tools to your app’s text views.
Configure text fields and custom views that accept text to handle input from Apple Pencil.
Deprecated
Avoid using deprecated classes and protocols in your apps.
Review unsupported symbols and their replacements.
Reference
This document describes constants that are used throughout the UIKit framework.
The UIKit framework defines data types that are used in multiple places throughout the framework.
The UIKit framework defines a number of functions, many of them used in graphics and drawing operations.
Structures
struct UIConfigurationTextAttributesTransformer
Defines a text transformation that can affect the visual appearance of a string.
https://developer.apple.com/documentation/uikit
Framework
UIKit
Construct and manage a graphical, event-driven user interface for your iOS, iPadOS, or tvOS app.
Overview
UIKit provides a variety of features for building apps, including components you can use to construct the core infrastructure of your iOS, iPadOS, or tvOS apps. The framework provides the window and view architecture for implementing your UI, the event-handling infrastructure for delivering Multi-Touch and other types of input to your app, and the main run loop for managing interactions between the user, the system, and your app.
UIKit also includes support for animations, documents, drawing and printing, text management and display, search, app extensions, resource management, and getting information about the current device. You can also customize accessibility support, and localize your app’s interface for different languages, countries, or cultural regions.
UIKit works seamlessly with the SwiftUI framework, so you can implement parts of your UIKit app in SwiftUI or mix interface elements between the two frameworks. For example, you can place UIKit views and view controllers inside SwiftUI views, and vice versa.
To build a macOS app, you can use SwiftUI to create an app that works across all of Apple’s platforms, or use AppKit to create an app for Mac only. Alternatively, you can bring your UIKit iPad app to the Mac with Mac Catalyst.
Topics
Essentials
Adopting Liquid Glass
Find out how to bring the new material to your app.
UIKit updates
Learn about important changes to UIKit.
About App Development with UIKit
Learn about the basic support that UIKit and Xcode provide for your iOS and tvOS apps.
Secure personal data, and respect user preferences for how data is used.
App structure
UIKit manages your app’s interactions with the system and provides classes for you to manage your app’s data and resources.
Manage life-cycle events and your app’s UI scenes, and get information about traits and the environment in which your app runs.
Organize your app’s data and share that data on the pasteboard.
Manage the images, strings, storyboards, and nib files that you use to implement your app’s interface.
Extend your app’s basic functionality to other parts of the system.
Display activity-based services to people.
Create a version of your iPad app that users can run on a Mac device.
User interface
Views help you display content onscreen and facilitate user interactions; view controllers help you manage views and the structure of your interface.
Present your content onscreen and define the interactions allowed with that content.
Manage your interface using view controllers and facilitate navigation around your app’s content.
Use stack views to lay out the views of your interface automatically. Use Auto Layout when you require precise placement of your views.
Apply Liquid Glass to views, support Dark Mode in your app, customize the appearance of bars, and use appearance proxies to modify your UI.
Provide feed
Responders and gesture recognizers help you handle touches and other events. Drag and drop, focus, peek and pop, and accessibility handle other user interactions.
Encapsulate your app’s event-handling logic in gesture recognizers so that you can reuse that code throughout your app.
Simplify interactions with your app using menu systems, contextual menus, Home Screen quick actions, and keyboard shortcuts.
Bring drag and drop to your app by using interaction APIs with your views.
Support pointer interactions in your custom controls and views.
Handle user interactions like double tap and squeeze on Apple Pencil.
Navigate the interface of your UIKit app using a remote, game controller, or keyboard.
Make your UIKit apps accessible to everyone who uses iOS and tvOS.
Graphics, drawing, and printing
UIKit provides classes and protocols that help you configure your drawing environment and render your content.
Create and manage images, including those that use bitmap and PDF formats.
Configure your app’s drawing environment using colors, renderers, draw paths, strings, and shadows.
Display the system print panels and manage the printing process.
Text
In addition to text views that simplify displaying text in your app, UIKit provides custom text management and rendering that supports the system keyboards.
Display text, manage fonts, and check spelling.
Manage text storage and perform custom layout of text-based content in your app’s views.
Configure the system keyboard, create your own keyboards to handle input, or detect key presses on a physical keyboard.
Add support for Writing Tools to your app’s text views.
Configure text fields and custom views that accept text to handle input from Apple Pencil.
Deprecated
Avoid using deprecated classes and protocols in your apps.
Review unsupported symbols and their replacements.
Reference
This document describes constants that are used throughout the UIKit framework.
The UIKit framework defines data types that are used in multiple places throughout the framework.
The UIKit framework defines a number of functions, many of them used in graphics and drawing operations.
Structures
struct UIConfigurationTextAttributesTransformer
Defines a text transformation that can affect the visual appearance of a string.
https://developer.apple.com/documentation/uikit/mac-catalyst
Collection
- UIKit
- Mac Catalyst
API Collection
Mac Catalyst
Create a version of your iPad app that users can run on a Mac device.
Overview
With Mac Catalyst, you can make a Mac version of your iPad app. Click the Mac checkbox in your iPad app’s project settings to configure the project to build both Mac and iPad versions of your app. The two apps share the same project and source code, making it easy to change your code in one place.
For information about designing a Mac version of your iPad app, see Mac Catalyst in the Human Interface Guidelines.
Topics
Essentials
Creating a Mac version of your iPad app
Bring your iPad app to macOS with Mac Catalyst.
App support
Bring an iPad App to the Mac with Mac Catalyst
Build a native Mac app from the same codebase as your iPad app.
Choosing a user interface idiom for your Mac app
Select the iPad or the Mac user interface idiom in your Mac app built with Mac Catalyst.
Optimizing your iPad app for Mac
Make your iPad app more like a Mac app by taking advantage of system features in macOS.
LSMinimumSystemVersion
The minimum version of the operating system required for the app to run in macOS.
UIApplicationSupportsTabbedSceneCollection
A Boolean value indicating whether an app built with Mac Catalyst supports automatic tabbing mode.
User interface
UIKit Catalog: Creating and customizing views and controls
Customize your app’s user interface with views and controls.
Building and improving your app with Mac Catalyst
Improve your iPadOS app with Mac Catalyst by supporting native controls, multiple windows, sharing, printing, menus and keyboard shortcuts.
Displaying a checkbox in your Mac app built with Mac Catalyst
Present a switch control as a Mac-style checkbox when your app runs in the Mac user interface idiom.
Removing the title bar in your Mac app built with Mac Catalyst
Display content that fills the entire height of a window by removing the title bar.
Provide a space for controls under a window’s title bar and above your custom content.
Touch Bar
Display interactive content and controls in the Touch Bar.
User interactions
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
Adding menus and shortcuts to the menu bar and user interface
Provide quick access to useful actions by adding menus and keyboard shortcuts to your Mac app built with Mac Catalyst.
Handling key presses made on a physical keyboard
Detect when someone presses and releases keys on a physical keyboard.
class UIHoverGestureRecognizer
A continuous gesture recognizer that interprets pointer movement over a view.
User preferences
Displaying a Preferences window
Provide a Preferences window in your Mac app built with Mac Catalyst so users can manage app preferences defined in a Settings bundle.
Detecting changes in the preferences window
Listen for and respond to a user’s preference changes in your Mac app built with Mac Catalyst using Combine.
Tooltips
Showing help tags for views and controls using tooltip interactions
Explain the purpose of interface elements by showing a tooltip when a person positions the pointer over the element.
class UIToolTipInteraction
An interaction object that makes it possible to show a tooltip when hovering a pointer over a view or control.
protocol UIToolTipInteractionDelegate
An interface that provides tooltip settings to an interaction.
See Also
App structure
Manage life-cycle events and your app’s UI scenes, and get information about traits and the environment in which your app runs.
Organize your app’s data and share that data on the pasteboard.
Manage the images, strings, storyboards, and nib files that you use to implement your app’s interface.
Extend your app’s basic functionality to other parts of the system.
Display activity-based services to people.
https://developer.apple.com/documentation/uikit/about-app-development-with-uikit
- UIKit
- About App Development with UIKit
Article
About App Development with UIKit
Learn about the basic support that UIKit and Xcode provide for your iOS and tvOS apps.
Overview
The UIKit framework provides the core objects that you need to build apps for iOS and tvOS. You use these objects to display your content onscreen, to interact with that content, and to manage interactions with the system. Apps rely on UIKit for their basic behavior, and UIKit provides many ways for you to customize that behavior to match your specific needs.
Xcode provides template projects as starting points for every app you create. For example, the following image shows the structure of an app created using the single view app template in Xcode. The template projects provide a minimal user interface, so you can build and run your project immediately and see the results on a device or in the simulator.
When you build your app, Xcode compiles your source files and creates an app bundle for your project. An app bundle is a structured directory that contains the code and resources associated with the app. Resources include the image assets, storyboard files, strings files, and app metadata that support your code. The structure of the app bundle is important, but Xcode knows where your resources need to go, so don’t worry about it for now.
Required Resources
Every UIKit app is required to have the following resources:
-
App icons
-
Launch screen storyboard
The system displays your app icon on the Home screen, in Settings, and anywhere it needs to differentiate your app from other apps. Because it is used in multiple places, and on multiple devices, you provide multiple versions of your app icon in your Xcode project’s AppIcon image asset. Your app icon should be distinctive to help the user identify your app quickly on the Home screen. However, you may vary the details of your icon to accommodate the different image sizes that you must provide.
The LaunchScreen.storyboard file contains your app’s initial user interface, and it can be a splash screen or a simplified version of your actual interface. When the user taps your app’s icon, the system displays your launch screen immediately, letting the user know that your app is now launching. The launch screen also provides cover for your app while it initializes itself. When your app is ready, the system hides the launch screen and reveals your app’s actual interface.
Required App Metadata
The system derives information about your app’s configuration and capabilities from the information property list ( Info.plist) file in your app bundle. Xcode provides a preconfigured version of this file with every new project template, but you will likely need to modify this file at some point. For example, if your app relies on specific hardware, or uses specific system frameworks, you might need to add information related to those features to this file.
One common modification you can make to the Info.plist file is to declare your app’s hardware and software requirements. These requirements are how you communicate to the system what your app needs to run. For example, a navigation app might require the presence of GPS hardware to provide turn-by-turn directions. The App Store prevents an app from being installed on a device that does not meet your app’s requirements.
For information about the keys that you can include in your Info.plist file, see Information Property List Key Reference.
Code Structure of a UIKit App
UIKit provides many of your app’s core objects, including those that interact with the system, run the app’s main event loop, and display your content onscreen. You use most of these objects as-is or with only minor modifications. Knowing which objects to modify, and when to modify them, is crucial to implementing your app.
The structure of UIKit apps is based on the Model-View-Controller (MVC) design pattern, wherein objects are divided by their purpose. Model objects manage the app’s data and business logic. View objects provide the visual representation of your data. Controller objects act as a bridge between your model and view objects, moving data between them at appropriate times.
The following image represents a fairly typical structure of a UIKit app. You provide the model objects that represent your app’s data structures. UIKit provides most of the view objects, although you can define custom views for your data, as needed. Coordinating the exchange of data between your data objects and the UIKit views are your view controllers and app delegate object.
The UIKit and Foundation frameworks provide many of the basic types that you use to define your app’s model objects. UIKit provides a UIDocument object for organizing the data structures that belong in a disk-based file. The Foundation framework defines basic objects representing strings, numbers, arrays, and other data types. The Swift Standard Library provides many of the same types available in the Foundation framework.
UIKit provides most of the objects in the controller and view layers of your app. Specifically, UIKit defines the UIView class, which is usually responsible for displaying your content onscreen. (You can also render content directly to the screen using Metal and other system frameworks.) The UIApplication object runs your app’s main event loop and manages your app’s overall life cycle.
See Also
Essentials
Adopting Liquid Glass
Find out how to bring the new material to your app.
UIKit updates
Learn about important changes to UIKit.
Secure personal data, and respect user preferences for how data is used.
https://developer.apple.com/documentation/uikit/protecting-the-user-s-privacy
Collection
- UIKit
- Protecting the User’s Privacy
Protecting the User’s Privacy
Secure personal data, and respect user preferences for how data is used.
Overview
Designing for user privacy is important. Most Apple devices contain personal data that the user doesn’t want to expose to apps or to external entities. If your app accesses or uses data inappropriately, the user might stop using your app and even delete it from their device.
Access user or device data only with the user’s informed consent obtained in accordance with applicable law. In addition, take appropriate steps to protect user and device data, and be transparent about how you use it.
Review Guidelines from Government and Industry Sources
Consult these documents:
-
Mobile Privacy Disclosures: Building Trust Through Transparency. The Federal Trade Commission’s report on mobile privacy.
-
Opinion 02/2013 on Apps on Smart Devices. The EU Data Protection Commissioners’ opinion on data protection for mobile apps.
-
Privacy on the Go: Recommendations for the Mobile Ecosystem. The California State Attorney General’s recommendations for mobile privacy.
-
Smartphone Privacy Initiative (2012) in English or Japanese and Smartphone Privacy Initiative II (2013) in English or Japanese. The Japanese Ministry of Internal Affairs and Communications’ Smartphone Privacy Initiatives.
Request Access Only When Your App Needs the Data
Request access to sensitive user or device data—like location, contacts, and photos—at the time your app needs the data. Supply a purpose string (sometimes called a usage description string) in your app’s Info.plist file that the system can present to a user explaining why your app needs access. Provide reasonable fallback behavior in situations where the user doesn’t grant access to the requested data. For more details, see Requesting access to protected resources.
Be Transparent About How Data Will Be Used
For example, when you submit your app to the App Store, specify a URL for your or statement as part of your App Store Connect metadata. You can also summarize that policy or statement in your app description.
Give the User Control Over Data and Protect Data You Collect
Respect the user’s preferences, and take reasonable steps to protect the data that you collect in your apps:
-
Provide settings that allow the user to disable access to sensitive information. The operating system does this automatically for protected system resources—like location, contacts, and health data—through the Privacy menu of the Settings app. Extend this behavior to any data you cache from these sources or collect directly. For example, if your users build a social media profile containing personal information, offer them a way to delete the data (including any server copies you have).
-
When storing files in iOS, use the strongest data protection level that works for your app, as described in Encrypting Your App’s Files. Use App Transport Security when sending user or device data over the network, as described in NSAppTransportSecurity.
-
If your app uses the
ASIdentifierManagerclass, respect the value of itsisAdvertisingTrackingEnabledproperty. If the user sets that property to false, then use theASIdentifierManagerclass only for limited advertising purposes, like frequency capping, attribution, conversion events, estimating the number of unique users, advertising fraud detection, and debugging. See the AdSupport framework for additional information. -
If you must identify users persistently, use the
identifierForVendorproperty of theUIDeviceclass or theadvertisingIdentifierproperty of theASIdentifierManagerclass.
Use the Minimum Amount of Data Required
Request and use the minimum amount of user or device data needed to accomplish a given task. Don’t seek access to or collect data for unnecessary or non-obvious reasons, or because you think it might be useful later.
If your app supports audio input, configure your audio session for recording only at the point where you actually plan to begin recording. Don’t configure your audio session for recording at launch time if you don’t plan to record right away. The system alerts users when apps configure their audio session for recording and gives the user the option to disable recording for your app.
Topics
Supporting Privacy
Requesting access to protected resources
Provide a purpose string that explains to a person why you need access to protected resources on their device.
Encrypting Your App’s Files
Protect the user’s data in iOS by encrypting it on disk.
See Also
Essentials
Adopting Liquid Glass
Find out how to bring the new material to your app.
UIKit updates
Learn about important changes to UIKit.
About App Development with UIKit
Learn about the basic support that UIKit and Xcode provide for your iOS and tvOS apps.
https://developer.apple.com/documentation/uikit/app-and-environment
Collection
- UIKit
- App and environment
API Collection
App and environment
Manage life-cycle events and your app’s UI scenes, and get information about traits and the environment in which your app runs.
Overview
In iOS 13 and later, a person can create and manage multiple instances of your app’s user interface simultaneously, and switch between them using the app switcher. On iPad, a person can also display multiple instances of your app side by side. Each instance of your UI displays different content, or displays the same content in a different way. For example, a person can display one instance of the Calendar app showing a specific day, and another showing an entire month.
UIKit communicates details about the current environment using trait collections, which reflect a combination of device settings, interface settings, and user preferences. For example, you use traits to detect whether Dark Mode is active for the current view or view controller. Consult the current trait collection of your UIView or UIViewController object when you want to customize its contents based on the current environment. Adopt the UITraitEnvironment protocol in other objects when you want them to receive trait notification changes.
Topics
Life cycle
Respond to system notifications when your app is in the foreground or background, and handle other significant system-related events.
Initialize your app’s data structures, prepare your app to run, and respond to any launch-time requests from the system.
class UIApplication
The centralized point of control and coordination for apps running in iOS.
protocol UIApplicationDelegate
A set of methods to manage shared behaviors for your app.
Manage multiple instances of your app’s UI simultaneously, and direct resources to the appropriate instance of your UI.
Device environment
class UIDevice
A representation of the current device.
class UIStatusBarManager
An object that describes the configuration of the status bar.
Adaptivity
Reduce the need to manually register for trait changes when you use traits within a method or closure that supports automatic trait tracking.
Responding to changing display modes on Apple TV
Change images and resources dynamically when the screen gamut on your device changes.
class UITraitCollection
A collection of data that represents the environment for an individual element in your app’s user interface.
protocol UITraitEnvironment
A set of methods that makes the iOS interface environment available to your app.
protocol UITraitChangeObservable
A type that calls your code in reaction to changes in the trait environment.
protocol UIMutableTraits
A mutable container of traits.
protocol UIAdaptivePresentationControllerDelegate
A set of methods that, in conjunction with a presentation controller, determine how to respond to trait changes in your app.
protocol UIContentContainer
A set of methods for adapting the contents of your view controllers to size and trait changes.
Custom traits
typealias UITrait
A type representing a trait in a trait collection.
protocol UITraitDefinition
iPad
Building a desktop-class iPad app
Optimize your iPad app’s user experience by adopting desktop-class enhancements for multitasking with Stage Manager, document interactions, text editing, search, and more.
Elevating your iPad app with a tab bar and sidebar
Provide a compact, ergonomic tab bar for quick access to key parts of your app, and a sidebar for in-depth navigation.
Supporting desktop-class features in your iPad app
Enhance your iPad app by adding desktop-class features and document support.
Implement multitasking APIs to seamlessly integrate your app with iPadOS.
Guided Access
protocol UIGuidedAccessRestrictionDelegate
A set of methods you use to add custom restrictions for the Guided Access feature in iOS.
Returns the restriction state for the specified guided access restriction.
Architecture
Ensure that your app behaves as expected by adapting it to support later versions of the operating system.
Creates the application object and the application delegate and sets up the event cycle.
See Also
App structure
Organize your app’s data and share that data on the pasteboard.
Manage the images, strings, storyboards, and nib files that you use to implement your app’s interface.
Extend your app’s basic functionality to other parts of the system.
Display activity-based services to people.
Create a version of your iPad app that users can run on a Mac device.
https://developer.apple.com/documentation/uikit/documents-data-and-pasteboard
Collection
- UIKit
- Documents, data, and pasteboard
API Collection
Documents, data, and pasteboard
Organize your app’s data and share that data on the pasteboard.
Topics
Documents
class UIDocument
An abstract base class for managing discrete portions of your app’s data.
class UIManagedDocument
A managed document object that integrates with Core Data.
Synchronizing documents in the iCloud environment
Manage documents across multiple devices to create a seamless editing and collaboration experience.
Document presentation
class UIDocumentViewController
A view controller that manages and presents a document stored locally or in the cloud.
Data management
protocol UIDataSourceModelAssociation
A set of methods that defines an interface for providing persistent references to data objects in your app.
Pasteboard
class UIPasteControl
A button that a person taps to place pasteboard contents in your app.
class Configuration
An object that determines a paste button’s color, corner style, icon, and text.
enum DisplayMode
Options that determine whether a paste button composes an icon, textual label, or both.
class UIPasteboard
An object that helps a user share data from one place to another within your app, and from your app to other apps.
class UIPasteConfiguration
The interface that an object implements to declare its ability to accept specific data types for pasting and for drag-and-drop activities.
protocol UIPasteConfigurationSupporting
The interface that determines whether a responder object supports paste configuration.
See Also
App structure
Manage life-cycle events and your app’s UI scenes, and get information about traits and the environment in which your app runs.
Manage the images, strings, storyboards, and nib files that you use to implement your app’s interface.
Extend your app’s basic functionality to other parts of the system.
Display activity-based services to people.
Create a version of your iPad app that users can run on a Mac device.
https://developer.apple.com/documentation/uikit/resource-management
Collection
- UIKit
- Resource management
API Collection
Resource management
Manage the images, strings, storyboards, and nib files that you use to implement your app’s interface.
Topics
Storyboards
Customizing the behavior of segue-based presentations
Pass data between view controllers during a segue, and programmatically control when segues occur.
Dismissing a view controller with an unwind segue
Configure an unwind segue in your storyboard file that dynamically chooses the most appropriate view controller to display next.
class UIStoryboard
An encapsulation of the design-time view controller graph represented in an Interface Builder storyboard resource file.
class UIStoryboardSegue
An object that prepares for and performs the visual transition between two view controllers.
class UIStoryboardUnwindSegueSource
An encapsulation of information about an unwind segue.
Assets
class UIImageAsset
A container for a collection of images that represent multiple ways of describing a single piece of artwork.
class NSDataAsset
An object from a data set type stored in an asset catalog.
Nib files
class UINib
An object that contains Interface Builder nib files.
See Also
App structure
Manage life-cycle events and your app’s UI scenes, and get information about traits and the environment in which your app runs.
Organize your app’s data and share that data on the pasteboard.
Extend your app’s basic functionality to other parts of the system.
Display activity-based services to people.
Create a version of your iPad app that users can run on a Mac device.
https://developer.apple.com/documentation/uikit/app-extensions
Collection
- UIKit
- App extensions
API Collection
App extensions
Extend your app’s basic functionality to other parts of the system.
Topics
Extension support
Use these Foundation classes to manage interactions between your app extension and its hosting app.
protocol NSExtensionRequestHandling : NSObjectProtocol
The interface an app extension uses to respond to a request from a host app.
class NSExtensionContext
The host app context from which an app extension is invoked.
Document provider
class NSFileProviderExtension
The principal class for the nonreplicated File Provider extension.
class UIDocumentPickerExtensionViewController
The principal class for the Document Picker View Controller extension.
Deprecated
Custom keyboard
protocol UITextDocumentProxy
An object that provides textual context to a custom keyboard.
protocol UIInputViewAudioFeedback
A property that enables a custom input or keyboard accessory view to play standard keyboard input clicks.
class UIInputViewController
The primary view controller for a custom keyboard app extension.
class UILexicon
A read-only array of term pairs, each in a lexicon entry object, for a custom keyboard.
class UILexiconEntry
A read-only term pair, available within a lexicon object, for a custom keyboard.
See Also
App structure
Manage life-cycle events and your app’s UI scenes, and get information about traits and the environment in which your app runs.
Organize your app’s data and share that data on the pasteboard.
Manage the images, strings, storyboards, and nib files that you use to implement your app’s interface.
Display activity-based services to people.
Create a version of your iPad app that users can run on a Mac device.
https://developer.apple.com/documentation/uikit/interprocess-communication
Collection
- UIKit
- Interprocess communication
API Collection
Interprocess communication
Display activity-based services to people.
Topics
User activities
class NSUserActivity
A representation of the state of your app at a moment in time.
protocol UIUserActivityRestoring
The protocol you adopt to restore an object’s state from a user activity.
Services
class UIActivity
An abstract class that you subclass to implement app-specific services.
class UIActivityViewController
A view controller that you use to offer standard services from your app.
protocol UIActivityItemSource
A set of methods that an activity view controller uses to retrieve the data items to act on.
class UIActivityItemProvider
A proxy for data that passes to an activity view controller.
See Also
App structure
Manage life-cycle events and your app’s UI scenes, and get information about traits and the environment in which your app runs.
Organize your app’s data and share that data on the pasteboard.
Manage the images, strings, storyboards, and nib files that you use to implement your app’s interface.
Extend your app’s basic functionality to other parts of the system.
Create a version of your iPad app that users can run on a Mac device.
https://developer.apple.com/documentation/uikit/views-and-controls
Collection
- UIKit
- Views and controls
API Collection
Views and controls
Present your content onscreen and define the interactions allowed with that content.
Overview
Views and controls are the visual building blocks of your app’s user interface. Use them to draw and organize your app’s content onscreen.
Views can host other views. Embedding one view inside another creates a containment relationship between the host view (known as the superview) and the embedded view (known as the subview). View hierarchies make it easier to manage views.
You can also use views to do any of the following:
-
Respond to touches and other events (either directly or in coordination with gesture recognizers).
-
Draw custom content using Core Graphics or UIKit classes.
-
Support drag and drop interactions.
-
Respond to focus changes.
-
Animate the size, position, and appearance attributes of the view.
UIView is the root class for all views and defines their common behavior. UIControl defines additional behaviors that are specific to buttons, switches, and other views designed for user interactions.
For additional information about how to use views and controls, see Human Interface Guidelines. To see examples of UIKit controls, see UIKit Catalog: Creating and customizing views and controls.
Topics
View fundamentals
class UIView
An object that manages the content for a rectangular area on the screen.
UIKit Catalog: Creating and customizing views and controls
Customize your app’s user interface with views and controls.
Container views
Organize and present large data sets using container views.
Autosizing Views for Localization in iOS
Add auto layout constraints to your app to achieve localizable views.
Display nested views using a configurable and highly customizable layout.
Display data in a single column of customizable rows.
class UIStackView
A streamlined interface for laying out a collection of views in either a column or a row.
class UIScrollView
A view that allows the scrolling and zooming of its contained views.
Content views
class UIActivityIndicatorView
A view that shows that a task is in progress.
class UICalendarView
A view that displays a calendar with date-specific decorations, and provides for user selection of a single date or multiple dates.
class UIContentUnavailableView
A view that indicates there’s no content to display.
class UIImageView
A view that displays a single image or a sequence of animated images in your interface.
class UIPickerView
A view that uses a spinning-wheel or slot-machine metaphor to show one or more sets of values.
class UIProgressView
A view that depicts the progress of a task over time.
class UIWebView
A view that embeds web content in your app.
Deprecated
Controls
Gather input and respond to user interactions with controls.
Responding to control-based events using target-action
Handle user input by connecting buttons, sliders, and other controls to your app’s code using the target-action design pattern.
class UIControl
The base class for controls, which are visual elements that convey a specific action or intention in response to user interactions.
class UIButton
A control that executes your custom code in response to user interactions.
class UIColorWell
A control that displays a color picker.
class UIDatePicker
A control for inputting date and time values.
class UIPageControl
A control that displays a horizontal series of dots, each of which corresponds to a page in the app’s document or other data-model entity.
class UISegmentedControl
A horizontal control that consists of multiple segments, each segment functioning as a discrete button.
class UISlider
A control for selecting a single value from a continuous range of values.
class UIStepper
A control for incrementing or decrementing a value.
class UISwitch
A control that offers a binary choice, such as on/off.
Text views
Display and edit text using text views.
class UILabel
A view that displays one or more lines of informational text.
class UITextField
An object that displays an editable text area in your interface.
class UITextView
A scrollable, multiline text region.
Extend the standard drag and drop support for text views to include custom types of content.
Search field
class UISearchTextField
A view for displaying and editing text and search tokens.
class UISearchToken
Search criteria in a search text field, represented by text and an optional icon.
protocol UISearchTextFieldDelegate
The interface for the delegate of a search field.
Visual effects
class UIVisualEffect
An initializer for visual effect views and blur and vibrancy effect objects.
class UIVisualEffectView
An object that implements some complex visual effects.
class UIVibrancyEffect
An object that amplifies and adjusts the color of the content layered behind a visual effect view.
class UIBlurEffect
An object that applies a blurring effect to the content layered behind a visual effect view.
Bars
Manage the items displayed on navigation bars, tab bars, search bars, and toolbars.
class UIBarItem
An abstract superclass for items that you can add to a bar that appears at the bottom of the screen.
class UIBarButtonItem
A specialized button for placement on a toolbar, navigation bar, or shortcuts bar.
class UIBarButtonItemGroup
A group of one or more bar button items for placement on a navigation bar or shortcuts bar.
class UINavigationBar
Navigational controls that display in a bar along the top of the screen, usually in conjunction with a navigation controller.
class UISearchBar
A specialized view for receiving search-related information from the user.
class UIToolbar
A control that displays one or more buttons along the bottom edge of your interface.
class UITabBar
A control that displays one or more buttons in a tab bar for selecting between different subtasks, views, or modes in an app.
class UITabBarItem
An object that describes an item in a tab bar.
protocol UIBarPositioning
A set of methods for defining the positioning of bars in iOS apps.
protocol UIBarPositioningDelegate
A set of methods that support the positioning of a bar that conforms to the UIBarPositioning protocol.
Content viewer
class UILargeContentViewerInteraction
An interaction that enables a gesture to present the large content viewer for cases when supporting the largest dynamic type sizes isn’t appropriate.
protocol UILargeContentViewerInteractionDelegate
An object that customizes the behavior of the large content viewer interactions.
protocol UILargeContentViewerItem
Methods that provide details about how to display your custom content in the large content viewer.
Private Click Measurement (PCM)
class UIEventAttributionView
An overlay view that verifies user interaction for Web AdAttributionKit.
class UIEventAttribution
An object that contains event attribution information for Web AdAttributionKit.
NSAdvertisingAttributionReportEndpoint
The URL where Private Click Measurement and SKAdNetwork send attribution information.
SwiftUI
Using SwiftUI with UIKit
Learn how to incorporate SwiftUI views into a UIKit app.
Related types
struct UIOffset
A structure that specifies an amount to offset a position.
struct UIAxis
A structure that specifies the layout axes.
struct UIEdgeInsets
The inset distances for views.
struct NSDirectionalEdgeInsets
The inset distances for views, taking the user interface layout direction into account.
struct NSDirectionalRectEdge
Constants that specify an edge or a set of edges, taking the user interface layout direction into account.
enum NSRectAlignment
Constants that specify alignment to an edge or a set of edges depending on the user interface layout direction.
struct UIDirectionalRectEdge
Macros that UIKit defines.
See Also
User interface
Manage your interface using view controllers and facilitate navigation around your app’s content.
Use stack views to lay out the views of your interface automatically. Use Auto Layout when you require precise placement of your views.
Apply Liquid Glass to views, support Dark Mode in your app, customize the appearance of bars, and use appearance proxies to modify your UI.
Provide feed
Provide a container for your view hierarchies and other content.
https://developer.apple.com/documentation/uikit/view-controllers
https://developer.apple.com/documentation/uikit/view-layout
https://developer.apple.com/documentation/uikit/appearance-customization
https://developer.apple.com/documentation/uikit/animation-and-haptics
https://developer.apple.com/documentation/uikit/windows-and-screens
https://developer.apple.com/documentation/uikit/touches-presses-and-gestures
https://developer.apple.com/documentation/uikit/menus-and-shortcuts
https://developer.apple.com/documentation/uikit/drag-and-drop
https://developer.apple.com/documentation/uikit/pointer-interactions
https://developer.apple.com/documentation/uikit/apple-pencil-interactions
https://developer.apple.com/documentation/uikit/focus-based-navigation
https://developer.apple.com/documentation/uikit/accessibility-for-uikit
https://developer.apple.com/documentation/uikit/images-and-pdf
https://developer.apple.com/documentation/uikit/drawing
https://developer.apple.com/documentation/uikit/printing
https://developer.apple.com/documentation/uikit/text-display-and-fonts
https://developer.apple.com/documentation/uikit/textkit
https://developer.apple.com/documentation/uikit/keyboards-and-input
https://developer.apple.com/documentation/uikit/writing-tools
https://developer.apple.com/documentation/uikit/handwriting-recognition
https://developer.apple.com/documentation/uikit/deprecated-symbols
Collection
- UIKit
- Deprecated symbols
API Collection
Deprecated symbols
Review unsupported symbols and their replacements.
Topics
Deprecated classes
class UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
Deprecated
class UIAlertView
A view that displays an alert message.
class UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
class UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
class UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
class UIMenuItem
A custom item in the editing menu managed by the menu controller.
class UIMutableUserNotificationAction
A modifiable version of the user notification action class.
class UIMutableUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
class UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
class UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
class UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
class UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
class UIUserNotificationCategory
class UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
Deprecated protocols
protocol UIAccelerometerDelegate
The interface for receiving acceleration-related data from the system.
protocol UIActionSheetDelegate
The interface for the delegate of an action sheet object.
protocol UIAlertViewDelegate
The interface for the delegate of an alert view object.
protocol UIPopoverControllerDelegate
The interface for the delegate of a popover controller object.
protocol UISearchDisplayDelegate
The interface for the delegate of a search display controller.
protocol UIViewControllerPreviewing
A set of methods that define the interface for configuring a previewing view controller on devices that support 3D Touch.
protocol UIViewControllerPreviewingDelegate
A set of methods used by the delegate to respond, with a preview view controller and a commit view controller, to the user pressing a view object on the screen of a device that supports 3D Touch.
Deprecated enumerations
enum UIStatusBarAnimation
Constants that specify the animation of the status bar as it’s hidden or made visible.
Deprecated functions
func UIApplicationMain(Int32, UnsafeMutablePointer<UnsafeMutablePointer<Int8>>!, String?, String?) -> Int32
Creates the application object and the application delegate and sets up the event cycle.
Deprecated samples
Implementing Peek and Pop
Accelerate actions in your app by providing shortcuts to preview content in detail view controllers.
https://developer.apple.com/documentation/uikit/uikit-enumerations
Collection
- UIKit
- UIKit Enumerations
API Collection
UIKit Enumerations
Topics
Enumerations
enum ExpandedStatus
enum ComponentSize
enum UIFocusItemDeferralMode
See Also
Reference
This document describes constants that are used throughout the UIKit framework.
The UIKit framework defines data types that are used in multiple places throughout the framework.
The UIKit framework defines a number of functions, many of them used in graphics and drawing operations.
https://developer.apple.com/documentation/uikit/uikit-constants
https://developer.apple.com/documentation/uikit/uikit-data-types
Collection
- UIKit
- UIKit Data Types
API Collection
UIKit Data Types
The UIKit framework defines data types that are used in multiple places throughout the framework.
Topics
Data Types
struct ComponentKey
struct Highlight
struct TextAlignment
struct TextList
See Also
Reference
This document describes constants that are used throughout the UIKit framework.
The UIKit framework defines a number of functions, many of them used in graphics and drawing operations.
https://developer.apple.com/documentation/uikit/uikit-functions
Collection
- UIKit
- UIKit Functions
API Collection
UIKit Functions
The UIKit framework defines a number of functions, many of them used in graphics and drawing operations.
Topics
See Also
Reference
This document describes constants that are used throughout the UIKit framework.
The UIKit framework defines data types that are used in multiple places throughout the framework.
https://developer.apple.com/documentation/uikit/uiconfigurationtextattributestransformer-swift.struct
- UIKit
- UIConfigurationTextAttributesTransformer
Structure
UIConfigurationTextAttributesTransformer
Defines a text transformation that can affect the visual appearance of a string.
Mac CatalystvisionOS
struct UIConfigurationTextAttributesTransformer
Overview
Use a transformer to affect how your attributed text appears on the UI. You provide a closure when initializing the transformer. Your closure accepts a container with the current text attributes and returns a container with the new text attributes.
let transformer = UIConfigurationTextAttributesTransformer { incoming in var outgoing = incoming outgoing.foregroundColor = UIColor.black outgoing.font = UIFont.boldSystemFont(ofSize: 20) return outgoing }
Topics
Creating a text attributes transformer
Creates a new text attributes transformer.
Defining a text transformation
A closure that defines the text transformation.
Calling a text transformer
Calls the transform closure of the text attributes transformer.
See Also
Configuring titles
var title: String?
The text of the title label the button displays.
var subtitle: String?
The text the subtitle label of the button displays.
var attributedTitle: AttributedString?
The text and style attributes for the button’s title label.
var attributedSubtitle: AttributedString?
The text and style attributes for the button’s subtitle label.
var titleTextAttributesTransformer: UIConfigurationTextAttributesTransformer?
A structure to update the attributed title when the button state changes.
var subtitleTextAttributesTransformer: UIConfigurationTextAttributesTransformer?
A structure to update the attributed subtitle when the button state changes.
var titlePadding: CGFloat
The distance between the title and subtitle labels.
var titleAlignment: UIButton.Configuration.TitleAlignment
The text alignment the button uses to lay out the title and subtitle.
enum TitleAlignment
Specifies how to align a button’s title and subtitle.
var titleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s title.
var subtitleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s subtitle.
https://developer.apple.com/documentation/uikit/mac-catalyst).
https://developer.apple.com/documentation/uikit/about-app-development-with-uikit)
https://developer.apple.com/documentation/uikit/protecting-the-user-s-privacy)
https://developer.apple.com/documentation/uikit/app-and-environment)
https://developer.apple.com/documentation/uikit/documents-data-and-pasteboard)
https://developer.apple.com/documentation/uikit/resource-management)
https://developer.apple.com/documentation/uikit/app-extensions)
https://developer.apple.com/documentation/uikit/interprocess-communication)
https://developer.apple.com/documentation/uikit/mac-catalyst)
https://developer.apple.com/documentation/uikit/views-and-controls)
https://developer.apple.com/documentation/uikit/view-controllers)
https://developer.apple.com/documentation/uikit/view-layout)
https://developer.apple.com/documentation/uikit/appearance-customization)
https://developer.apple.com/documentation/uikit/animation-and-haptics)
https://developer.apple.com/documentation/uikit/windows-and-screens)
https://developer.apple.com/documentation/uikit/touches-presses-and-gestures)
https://developer.apple.com/documentation/uikit/menus-and-shortcuts)
https://developer.apple.com/documentation/uikit/drag-and-drop)
https://developer.apple.com/documentation/uikit/pointer-interactions)
https://developer.apple.com/documentation/uikit/apple-pencil-interactions)
https://developer.apple.com/documentation/uikit/focus-based-navigation)
https://developer.apple.com/documentation/uikit/accessibility-for-uikit)
https://developer.apple.com/documentation/uikit/images-and-pdf)
https://developer.apple.com/documentation/uikit/drawing)
https://developer.apple.com/documentation/uikit/printing)
https://developer.apple.com/documentation/uikit/text-display-and-fonts)
https://developer.apple.com/documentation/uikit/textkit)
https://developer.apple.com/documentation/uikit/keyboards-and-input)
https://developer.apple.com/documentation/uikit/writing-tools)
https://developer.apple.com/documentation/uikit/handwriting-recognition)
https://developer.apple.com/documentation/uikit/deprecated-symbols)
https://developer.apple.com/documentation/uikit/uikit-enumerations)
https://developer.apple.com/documentation/uikit/uikit-constants)
https://developer.apple.com/documentation/uikit/uikit-data-types)
https://developer.apple.com/documentation/uikit/uikit-functions)
https://developer.apple.com/documentation/uikit/uiconfigurationtextattributestransformer-swift.struct)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument
- UIKit
- UIDocument
Class
UIDocument
An abstract base class for managing discrete portions of your app’s data.
@MainActor class UIDocument
Mentioned in
Customizing a document-based app’s launch experience
About App Development with UIKit
Overview
Apps that make use of UIDocument and its underlying architecture get many benefits for their documents:
-
Asynchronous reading and writing of data on a background queue, meaning your app’s responsiveness is unaffected while reading and writing operations take place
-
Coordinated reading and writing of document files automatically integrated with cloud services
-
Support for discovering conflicts between different versions of a document
-
Safe-saving of document data by writing data first to a temporary file and then replacing the current document file with it
-
Automatic saving of document data at opportune moments and support for dealing with suspend behaviors
In the Model-View-Controller design pattern, a UIDocument object is a model object or model-controller object — it manages the data of a document or the aggregate model objects that together constitute the document’s data. You typically pair it with a view controller that manages the view presenting the document’s contents. UIDocument provides no direct support for managing document views, but view controllers that subclass UIDocumentViewController can present a UIDocument, and view controllers that subclass UIDocumentBrowserViewController can organize and display UIDocument collections.
Document-based apps include those that can generate multiple documents, each with its own file-system location. A document-based app must create a subclass of UIDocument for its documents.
The primary attribute of a document in the UIDocument architecture is its file URL. When you initialize an instance of your document subclass by calling init(fileURL:), you must pass a file URL locating the document file in the app sandbox. UIDocument determines the file type (the Uniform Type Identifier associated with the file extension) and the document name (the filename component) from the file URL. You can override the accessor methods of the fileType and localizedName properties to supply different values.
The following outlines the life cycle of a typical document:
- You create a new document or open an existing document.
-
To create a new document, allocate and initialize an instance of your subclass and then call
save(to:for:completionHandler:)on the instance. -
To open an existing document (selected by the user), allocate and initialize an instance of your subclass and then call
open(completionHandler:)on the instance.
-
The user edits the document. As the user edits, track changes to the document.
UIDocumentperiodically notes when there are unsaved changes and writes the document data to its file. -
The user requests that the document be integrated with cloud services (optional). You must enable the document for cloud storage. You must also resolve any conflicts between different versions of the same document.
-
The user closes the document. Call
close(completionHandler:)on the document instance.UIDocumentsaves the document if there are any unsaved changes.
A typical document-based app calls open(completionHandler:), close(completionHandler:), and save(to:for:completionHandler:) on the main thread. When the read or save operation kicked off by these methods concludes, the system executes the completion-handler block on the same dispatch queue as the system used to invoke the method, allowing you to complete any tasks contingent on the read or save operation. If the operation isn’t successful, the system passes false to the completion-handler block.
Implement the NSFilePresenter protocol
The UIDocument class adopts the NSFilePresenter protocol. When another client attempts to read the document of a UIDocument-based app, the system suspends reading until the system provides the UIDocument object an opportunity to save any changes made to the document.
Although some implementations do nothing, UIDocument implements all NSFilePresenter methods. Specifically, UIDocument:
-
Implements
relinquishPresentedItem(toReader:)to forward the incoming block toperformAsynchronousFileAccess(_:) -
Implements
relinquishPresentedItem(toWriter:)to check if the file-modification date changed; if the file is newer than before, it callsrevert(toContentsOf:completionHandler:)with the value of thefileURLas the URL parameter -
Implements
presentedItemDidMove(to:)to update the document’s file URL (fileURL)
In your UIDocument subclass, if you override a NSFilePresenter method, you can always invoke the superclass implementation ( super).
Create a subclass
Each document-based app must create a subclass of UIDocument whose instances represent its documents. The subclassing requirements for most apps are simple:
-
For writing operations, implement the
contents(forType:)method to provide a snapshot of document data. The data must be in the form of anNSDataobject (for flat files) or anFileWrapperobject (for file packages). Writing operations are usually initiated through the autosave feature. -
For reading operations, implement the
load(fromContents:ofType:)method to receive anNSDataorFileWrapperobject and initialize the app’s data structures with it. -
Implement change tracking to enable the autosaving feature. See Track changes for details.
-
When cloud services are enabled for a document, resolve conflicts between different versions of a document. See Resolve conflicts and handle errors for details.
The system typically calls the contents(forType:) and load(fromContents:ofType:) methods on the main queue. More specifically:
-
The system calls the
contents(forType:)method on the queue that the system called thesave(to:for:completionHandler:)method on; writing of data takes place on a background thread. -
The system calls the
load(fromContents:ofType:)method on the queue that the system called theopen(completionHandler:)method on.
If you have special requirements for reading and writing document data for which the contents(forType:) and load(fromContents:ofType:) methods won’t suffice, you can override other methods of the UIDocument class. See Override input and output methods for a discussion of these requirements and methods.
Track changes
To enable the autosaving feature of UIDocument, you must notify it when users make changes to a document. UIDocument periodically checks whether the hasUnsavedChanges method returns true; if it does, it initiates the save operation for the document.
There are two primary ways to implement change tracking in your UIDocument subclass:
-
Call the methods of the
UndoManagerclass to implement undo and redo for the document. You can access the defaultUndoManagerobject from theundoManagerproperty. This is the preferred approach, especially for existing apps that already support undo and redo. -
Call the
updateChangeCount(_:)method at the appropriate junctures in your code.
Resolve conflicts and handle errors
A UIDocument object has a specific state at any moment in its life cycle. You can check the current state by querying the documentState property, and get notified about changes by observing the stateChangedNotification notification.
If the owner enables a document for iCloud, it’s important to check for conflicting versions and to attempt to resolve conflicts. Listen for the stateChangedNotification notification and then checking if the document state is inConflict. This state indicates that there are conflicting versions of the document, which you can access by calling the NSFileVersion class method unresolvedConflictVersionsOfItem(at:), passing in the document’s file URL. If you can resolve a conflict correctly without user interaction, do so. Otherwise, discretely notify the user that a conflict exists and let them choose how to resolve it. Possible approaches include:
-
Display the conflicting versions, from which a user can pick one or both versions to keep.
-
Display a merged version and giving the user an option to pick it.
-
Display the file modification dates and giving the user the option to choose one or both.
Document state, in addition to indicating an inter-file conflict, can indicate errors. For example, closed indicates an error in reading, and savingError indicates an error in saving or reverting a document. The system notifies your app of reading and writing errors through the success parameter passed into the completion handlers of the open(completionHandler:), close(completionHandler:), revert(toContentsOf:completionHandler:), and save(to:for:completionHandler:) methods.
You can handle errors by calling or implementing the handleError(_:userInteractionPermitted:) method; the default implementations of the open(completionHandler:) and save(to:for:completionHandler:) methods call handleError(_:userInteractionPermitted:) when a UIDocument object encounters a reading or writing error, respectively. You can handle read, save, and reversion errors by informing the user and, if the situation permits, trying to recover from the error.
Be sure to read the description for the contents(forType:) method for its guidance on handling errors encountered during document saving.
Override input and output methods
If you app has special requirements for reading or writing document data, it can override methods of UIDocument other than load(fromContents:ofType:) and contents(forType:). These requirements often include the following:
- Incremental reading and writing of large data files
Override the read(from:) and writeContents(_:to:for:originalContentsURL:) methods, respectively.
- Custom representations of document data (that is, not an
NSDataorFileWrapperobject)
Override the read(from:) method when reading document data and the writeContents(_:to:for:originalContentsURL:) method when writing document data.
- Performing actions before or after reading or writing data
Override open(completionHandler:) and save(to:for:completionHandler:).
- A custom approach to safe-saving
Override the writeContents(_:andAttributes:safelyTo:for:) method.
- Changing the file type of a document before it’s saved
Override the savingFileType method to return a file type other than the default ( fileType). An example of this is an RTF document which, after a user adds an image to it, should be saved as an RTFD document.
If you override these methods, be aware that all reading and writing of document data must be done on a background queue and must be coordinated with other attempts to read from and write to the same document file. Because of this, you usually call the superclass implementation ( super) as part of your override, and if you call other UIDocument methods, you usually invoke them in the block passed into a call of the performAsynchronousFileAccess(_:) method. Read the method descriptions for details.
Access document attributes
If you override any of the document-attribute properties (listed under Accessing document attributes) by overriding the related accessor methods, be aware that the UIKit framework can call these accessor methods on a background thread. Thus your overriding implementation must be thread safe.
Rename documents
UIDocument provides support for changing the document’s title. Security considerations require that clients can’t programmatically rename a file on the file system, and that the system confirms that a person intends to rename their file. To satisfy these restrictions, the system, instead of your app, presents a renaming user interface using a process outside your app. The external process renames the underlying file and reports the new location and handles the rename request internally when a person invokes renaming from the title menu. If you’re using UIDocumentViewController, it automatically configures renaming for you. Otherwise, you manually assign the document as the navigation item’s renameDelegate.
init(document: MyDocument) { self.document = document super.init(nibName:nil, bundle: nil) self.navigationItem.renameDelegate = document }
The Rename action appears in the title menu as one of the system-suggested actions. When a person taps the Rename action, the system shows an inline text field for changing the navigation item’s title. Upon renaming the item, the system changes the file name in storage as though the person renamed the file in another application.
Prior to iOS 17, to enable the system rename user interface, a client view controller adopts the UINavigationItemRenameDelegate protocol and assigns itself as the navigation item’s renameDelegate. It’s the client’s responsibility to implement callbacks such as navigationItem(_:didEndRenamingWith:) (Swift) or navigationItem:didEndRenamingWithTitle: (Objective-C) to explicitly move the file in storage.
class EditorViewController: UIViewController, UINavigationItemRenameDelegate {
override func viewDidLoad() { super.viewDidLoad() navigationItem.renameDelegate = self }
func navigationItem(_ navigationItem: UINavigationItem, didEndRenamingWith: title: String) { // Move the file, update the model, and so on. } }
Topics
Initializing a document object
init(fileURL: URL)
Returns a document object initialized with its file-system location.
Accessing document attributes
var fileURL: URL
The file URL you use to initialize the document.
var localizedName: String
The localized name of the document.
var fileType: String?
The file type of the document.
var fileModificationDate: Date?
The date and time your app last modified the document file.
var documentState: UIDocument.State
The current state of the document.
var progress: Progress?
The upload or download progress of a document.
Writing document data
Asynchronously closes the document after saving any changes.
Returns the document data to be saved.
Saves document data to the specified location in the application sandbox.
Ensures that document data is written safely to a specified location in the application sandbox.
func writeContents(Any, to: URL, for: UIDocument.SaveOperation, originalContentsURL: URL?) throws
Writes the document data to disk at the sandbox location indicated by a file URL.
var savingFileType: String?
Returns the file type to use for saving a document.
Returns a dictionary of file attributes to associate with the document file when writing or updating it.
Returns a file extension to append to the file URL of the document file being written.
Reading document data
Opens a document asynchronously.
func load(fromContents: Any, ofType: String?) throws
Loads the document data into the app’s data model.
func read(from: URL) throws
Reads the document data in a file at a specified location in the application sandbox.
Creating new documents
struct CreationIntent
An app intent that creates new documents for your app.
Accessing document files asynchronously
Schedules a document-reading or document-writing operation on a concurrent background queue.
Reverting a document
Reverts a document to the most recent document data stored on-disk.
Disabling and enabling editing
func disableEditing()
Disables editing when it’s unsafe to make changes to a document.
func enableEditing()
Enables editing when it’s safe again to make changes to a document.
Tracking changes and autosaving
var hasUnsavedChanges: Bool
A Boolean value that indicates whether the document has any unsaved changes.
func updateChangeCount(UIDocument.ChangeKind)
Updates the change counter by indicating the kind of change.
var undoManager: UndoManager!
The undo manager for the document.
Returns a change token for a specific save operation.
func updateChangeCount(withToken: Any, for: UIDocument.SaveOperation)
Updates the change count with reference to a change-count token passed in by UIKit.
Initiates automatic saving of documents with unsaved changes.
Supporting user activities
var userActivity: NSUserActivity?
An object encapsulating a user activity supported by this document.
func restoreUserActivityState(NSUserActivity)
Restores the state needed to continue the given user activity.
func updateUserActivityState(NSUserActivity)
Updates the state of the given user activity.
Resolving conflicts and handling errors
func handleError(any Error, userInteractionPermitted: Bool)
Handles an error that occurs during an attempt to read, save, or revert a document.
func finishedHandlingError(any Error, recovered: Bool)
Tells UIKit that you finished handling the error.
func userInteractionNoLongerPermitted(forError: any Error)
Indicates when it’s no longer safe to proceed without immediately handling the error.
Constants
enum ChangeKind
Constants that specify the kind of change to a document.
enum SaveOperation
Constants that specify the type of save operation.
struct State
Constants that specify the document state.
class let userActivityURLKey: String
The key that identifies the document associated with a user activity.
Notifications
class let stateChangedNotification: NSNotification.Name
A notification the document object posts when there’s a change in the state of the document.
Structures
struct StateChangedMessage Beta
Relationships
Inherits From
NSObject
Inherited By
UIManagedDocument
Conforms To
CVarArgCopyableCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSFilePresenterNSObjectProtocolProgressReportingSendableUIUserActivityRestoring
See Also
Documents
class UIManagedDocument
A managed document object that integrates with Core Data.
Synchronizing documents in the iCloud environment
Manage documents across multiple devices to create a seamless editing and collaboration experience.
https://developer.apple.com/documentation/uikit/uiview
- UIKit
- UIView
Class
UIView
An object that manages the content for a rectangular area on the screen.
tvOS
@MainActor class UIView
Mentioned in
Using responders and the responder chain to handle events
Customizing a document-based app’s launch experience
Customizing drawings
Implementing a Multi-Touch app
Making a view into a drag source
Overview
Views are the fundamental building blocks of your app’s user interface, and the UIView class defines the behaviors that are common to all views. A view object renders content within its bounds rectangle, and handles any interactions with that content. The UIView class is a concrete class that you can instantiate and use to display a fixed background color. You can also subclass it to draw more sophisticated content. To display labels, images, buttons, and other interface elements commonly found in apps, use the view subclasses that the UIKit framework provides rather than trying to define your own.
Because view objects are the main way your application interacts with the user, they have a number of responsibilities. Here are just a few:
-
Drawing and animation
-
Views draw content in their rectangular area using UIKit or Core Graphics.
-
You can animate some view properties to new values.
-
Layout and subview management
-
Views may contain zero or more subviews.
-
Views can adjust the size and position of their subviews.
-
Use Auto Layout to define the rules for resizing and repositioning your views in response to changes in the view hierarchy.
-
Event handling
-
A view is a subclass of
UIResponderand can respond to touches and other types of events. -
Views can install gesture recognizers to handle common gestures.
Views can nest inside other views to create view hierarchies, which offer a convenient way to organize related content. Nesting a view creates a parent-child relationship between the nested child view (known as the subview) and the parent (known as the superview). A parent view may contain any number of subviews, but each subview has only one superview. By default, when a subview’s visible area extends outside of the bounds of its superview, no clipping of the subview’s content occurs. Use the clipsToBounds property to change that behavior.
The frame and bounds properties define the geometry of each view. The frame property defines the origin and dimensions of the view in the coordinate system of its superview. The bounds property defines the internal dimensions of the view as it sees them, and its use is almost exclusive to custom drawing code. The center property provides a convenient way to reposition a view without changing its frame or bounds properties directly.
For detailed information about how to use the UIView class, see View Programming Guide for iOS.
Create a view
Normally, you create views in your storyboards by dragging them from the library to your canvas. You can also create views programmatically. When creating a view, you typically specify its initial size and position relative to its future superview. For example, the following example creates a view and places its top-left corner at the point (10, 10) in the superview’s coordinate system (once it is added to that superview).
let rect = CGRect(x: 10, y: 10, width: 100, height: 100) let myView = UIView(frame: rect)
CGRect viewRect = CGRectMake(10, 10, 100, 100); UIView* myView = [[UIView alloc] initWithFrame:viewRect];
To add a subview to another view, call the addSubview(_:) method on the superview. You may add any number of subviews to a view, and sibling views may overlap each other without any issues in iOS. Each call to the addSubview(_:) method places the new view on top of all other siblings. You can specify the relative z-order of subview by adding it using the insertSubview(_:aboveSubview:) and insertSubview(_:belowSubview:) methods. You can also exchange the position of already added subviews using the exchangeSubview(at:withSubviewAt:) method.
After creating a view, create Auto Layout rules to govern how the size and position of the view change in response to changes in the rest of the view hierarchy. For more information, see Auto Layout Guide.
Draw views
View drawing occurs on an as-needed basis. When a view is first shown, or when all or part of it becomes visible due to layout changes, the system asks the view to draw its contents. For views that contain custom content using UIKit or Core Graphics, the system calls the view’s draw(_:) method. Your implementation of this method is responsible for drawing the view’s content into the current graphics context, which is set up by the system automatically prior to calling this method. This creates a static visual representation of your view’s content that can then be displayed on the screen.
When the actual content of your view changes, it’s your responsibility to notify the system that your view needs to be redrawn. You do this by calling your view’s setNeedsDisplay() or setNeedsDisplay(_:) method of the view. These methods let the system know that it should update the view during the next drawing cycle. Because it waits until the next drawing cycle to update the view, you can call these methods on multiple views to update them at the same time.
For detailed information about the view drawing cycle and the role your views have in this cycle, see View Programming Guide for iOS.
Animate views
Changes to several view properties can be animated — that is, changing the property creates an animation starting at the current value and ending at the new value that you specify. The following properties of the UIView class are animatable:
-
frame -
bounds -
center -
transform -
alpha -
backgroundColor
To animate your changes, create a UIViewPropertyAnimator object and use its handler block to change the values of your view’s properties. The UIViewPropertyAnimator class lets you specify the duration and timing of your animations, but it performs the actual animations. You can pause a property-based animator that’s currently running to interrupt the animation and drive it interactively. For more information, see UIViewPropertyAnimator.
Threading considerations
Manipulations to your app’s user interface must occur on the main thread. Thus, you should always call the methods of the UIView class from code running in the main thread of your app. The only time this may not be strictly necessary is when creating the view object itself, but all other manipulations should occur on the main thread.
Subclassing notes
The UIView class is a key subclassing point for visual content that also requires user interactions. Although there are many good reasons to subclass UIView, it is recommended that you do so only when the basic UIView class or the standard system views do not provide the capabilities that you need. Subclassing requires more work on your part to implement the view and to tune its performance.
For information about ways to avoid subclassing, see Alternatives to subclassing.
Methods to override
When subclassing UIView, there are only a handful of methods you should override and many methods that you might override depending on your needs. Because UIView is a highly configurable class, there are also many ways to implement sophisticated view behaviors without overriding custom methods, which are discussed in the Alternatives to Subclassing section. In the meantime, the following list includes the methods you might consider overriding in your UIView subclasses:
-
Initialization:
-
init(frame:)- It is recommended that you implement this method. You can also implement custom initialization methods in addition to, or instead of, this method. -
doc://com.apple.documentation/documentation/oslog/oslogentry/init(coder:) - Implement this method if you load your view from storyboards or nib files and your view requires custom initialization.
-
layerClassUse this property only if you want your view to use a different Core Animation layer for its backing store. For example, if your view uses tiling to display a large scrollable area, you might want to set the property to theCATiledLayerclass. -
Drawing and printing:
-
draw(_:)- Implement this method if your view draws custom content. If your view does not do any custom drawing, avoid overriding this method. -
draw(_:for:)- Implement this method only if you want to draw your view’s content differently during printing. -
Layout and Constraints:
-
requiresConstraintBasedLayoutUse this property if your view class requires constraints to work properly. -
updateConstraints()- Implement this method if your view needs to create custom constraints between your subviews. -
alignmentRect(forFrame:),frame(forAlignmentRect:)- Implement these methods to override how your views are aligned to other views. -
didAddSubview(_:),willRemoveSubview(_:)- Implement these methods as needed to track the additions and removals of subviews. -
willMove(toSuperview:),didMoveToSuperview()- Implement these methods as needed to track the movement of the current view in your view hierarchy. -
Event Handling:
-
gestureRecognizerShouldBegin(_:)- Implement this method if your view handles touch events directly and might want to prevent attached gesture recognizers from triggering additional actions. -
touchesBegan(_:with:),touchesMoved(_:with:),touchesEnded(_:with:),touchesCancelled(_:with:)- Implement these methods if you need to handle touch events directly. (For gesture-based input, use gesture recognizers.)
Alternatives to subclassing
Many view behaviors can be configured without the need for subclassing. Before you start overriding methods, consider whether modifying the following properties or behaviors would provide the behavior you need.
-
addConstraint(_:)- Define automatic layout behavior for the view and its subviews. -
autoresizingMask- Provides automatic layout behavior when the superview’s frame changes. These behaviors can be combined with constraints. -
contentMode- Provides layout behavior for the view’s content, as opposed to theframeof the view. This property also affects how the content is scaled to fit the view and whether it is cached or redrawn. -
isHiddenoralpha- Change the transparency of the view as a whole rather than hiding or applying alpha to your view’s rendered content. -
backgroundColor- Set the view’s color rather than drawing that color yourself. -
Subviews - Rather than draw your content using a
draw(_:)method, embed image and label subviews with the content you want to present. -
Gesture recognizers - Rather than subclass to intercept and handle touch events yourself, you can use gesture recognizers to send an action to a target object.
-
Animations - Use the built-in animation support rather than trying to animate changes yourself. The animation support provided by Core Animation is fast and easy to use.
-
Image-based backgrounds - For views that display relatively static content, consider using a
UIImageViewobject with gesture recognizers instead of subclassing and drawing the image yourself. Alternatively, you can also use a genericUIViewobject and assign your image as the content of the view’sCALayerobject.
Animations are another way to make visible changes to a view without requiring you to subclass and implement complex drawing code. Many properties of the UIView class are animatable, which means changes to those properties can trigger system-generated animations. Starting animations requires as little as one line of code to indicate that any changes that follow should be animated. For more information about animation support for views, see Animate views.
Topics
Creating a view object
init(frame: CGRect)
Creates a view with the specified frame rectangle.
init?(coder: NSCoder)
Creates a view from data in an unarchiver.
Configuring a view’s visual appearance
var backgroundColor: UIColor?
The view’s background color.
var isHidden: Bool
A Boolean value that determines whether the view is hidden.
var alpha: CGFloat
The view’s alpha value.
var isOpaque: Bool
A Boolean value that determines whether the view is opaque.
var tintColor: UIColor!
The first nondefault tint color value in the view’s hierarchy, ascending from and starting with the view itself.
var tintAdjustmentMode: UIView.TintAdjustmentMode
The first non-default tint adjustment mode value in the view’s hierarchy, ascending from and starting with the view itself.
var clipsToBounds: Bool
A Boolean value that determines whether subviews are confined to the bounds of the view.
var clearsContextBeforeDrawing: Bool
A Boolean value that determines whether the view’s bounds should be automatically cleared before drawing.
var mask: UIView?
An optional view whose alpha channel is used to mask a view’s content.
class var layerClass: AnyClass
Returns the class used to create the layer for instances of this class.
var layer: CALayer
The view’s Core Animation layer to use for rendering.
Configuring the event-related behavior
var isUserInteractionEnabled: Bool
A Boolean value that determines whether user events are ignored and removed from the event queue.
var isMultipleTouchEnabled: Bool
A Boolean value that indicates whether the view receives more than one touch at a time.
var isExclusiveTouch: Bool
A Boolean value that indicates whether the receiver handles touch events exclusively.
Configuring the bounds and frame rectangles
var frame: CGRect
The frame rectangle, which describes the view’s location and size in its superview’s coordinate system.
var bounds: CGRect
The bounds rectangle, which describes the view’s location and size in its own coordinate system.
var center: CGPoint
The center point of the view’s frame rectangle.
var transform: CGAffineTransform
Specifies the transform applied to the view, relative to the center of its bounds.
var transform3D: CATransform3D
The three-dimensional transform to apply to the view.
var anchorPoint: CGPoint
The anchor point of the view’s bounds rectangle.
Managing the view hierarchy
var superview: UIView?
The receiver’s superview, or nil if it has none.
The receiver’s immediate subviews.
var window: UIWindow?
The receiver’s window object, or nil if it has none.
func addSubview(UIView)
Adds a view to the end of the receiver’s list of subviews.
func bringSubviewToFront(UIView)
Moves the specified subview so that it appears on top of its siblings.
func sendSubviewToBack(UIView)
Moves the specified subview so that it appears behind its siblings.
func removeFromSuperview()
Unlinks the view from its superview and its window, and removes it from the responder chain.
func insertSubview(UIView, at: Int)
Inserts a subview at the specified index.
func insertSubview(UIView, aboveSubview: UIView)
Inserts a view above another view in the view hierarchy.
func insertSubview(UIView, belowSubview: UIView)
Inserts a view below another view in the view hierarchy.
func exchangeSubview(at: Int, withSubviewAt: Int)
Exchanges the subviews at the specified indices.
Returns a Boolean value indicating whether the receiver is a subview of a given view or identical to that view.
Observing view-related changes
func didAddSubview(UIView)
Tells the view that a subview was added.
func willRemoveSubview(UIView)
Tells the view that a subview is about to be removed.
func willMove(toSuperview: UIView?)
Tells the view that its superview is about to change to the specified superview.
func didMoveToSuperview()
Tells the view that its superview changed.
func willMove(toWindow: UIWindow?)
Tells the view that its window object is about to change.
func didMoveToWindow()
Tells the view that its window object changed.
Observing trait changes
protocol UITraitChangeObservable
A type that calls your code in reaction to changes in the trait environment.
Requesting trait updates
func updateTraitsIfNeeded()
Overriding trait values
var traitOverrides: UITraitOverrides
struct UITraitOverrides
Configuring content margins
Positioning content within layout margins
Position views so that they aren’t crowded by other content.
var directionalLayoutMargins: NSDirectionalEdgeInsets
The default spacing to use when laying out content in a view, taking into account the current language direction.
var layoutMargins: UIEdgeInsets
The default spacing to use when laying out content in the view.
var preservesSuperviewLayoutMargins: Bool
A Boolean value indicating whether the current view also respects the margins of its superview.
func layoutMarginsDidChange()
Notifies the view that the layout margins changed.
Getting the safe area
Positioning content relative to the safe area
Position views so that they aren’t obstructed by other content.
var safeAreaInsets: UIEdgeInsets
The insets that you use to determine the safe area for this view.
var safeAreaLayoutGuide: UILayoutGuide
The layout guide representing the portion of your view that is unobscured by bars and other content.
func safeAreaInsetsDidChange()
Called when the safe area of the view changes.
var insetsLayoutMarginsFromSafeArea: Bool
A Boolean value indicating whether the view’s layout margins are updated automatically to reflect the safe area.
Managing the view’s constraints
Adjust the size and position of the view using Auto Layout constraints.
var constraints: [NSLayoutConstraint]
The constraints held by the view.
func addConstraint(NSLayoutConstraint)
Adds a constraint on the layout of the receiving view or its subviews.
func addConstraints([NSLayoutConstraint])
Adds multiple constraints on the layout of the receiving view or its subviews.
func removeConstraint(NSLayoutConstraint)
Removes the specified constraint from the view.
func removeConstraints([NSLayoutConstraint])
Removes the specified constraints from the view.
Creating constraints using layout anchors
Attach Auto Layout constraints to one of the view’s anchors.
var bottomAnchor: NSLayoutYAxisAnchor
A layout anchor representing the bottom edge of the view’s frame.
var centerXAnchor: NSLayoutXAxisAnchor
A layout anchor representing the horizontal center of the view’s frame.
var centerYAnchor: NSLayoutYAxisAnchor
A layout anchor representing the vertical center of the view’s frame.
var firstBaselineAnchor: NSLayoutYAxisAnchor
A layout anchor representing the baseline for the topmost line of text in the view.
var heightAnchor: NSLayoutDimension
A layout anchor representing the height of the view’s frame.
var lastBaselineAnchor: NSLayoutYAxisAnchor
A layout anchor representing the baseline for the bottommost line of text in the view.
var leadingAnchor: NSLayoutXAxisAnchor
A layout anchor representing the leading edge of the view’s frame.
var leftAnchor: NSLayoutXAxisAnchor
A layout anchor representing the left edge of the view’s frame.
var rightAnchor: NSLayoutXAxisAnchor
A layout anchor representing the right edge of the view’s frame.
var topAnchor: NSLayoutYAxisAnchor
A layout anchor representing the top edge of the view’s frame.
var trailingAnchor: NSLayoutXAxisAnchor
A layout anchor representing the trailing edge of the view’s frame.
var widthAnchor: NSLayoutDimension
A layout anchor representing the width of the view’s frame.
Working with layout guides
func addLayoutGuide(UILayoutGuide)
Adds the specified layout guide to the view.
var layoutGuides: [UILayoutGuide]
The array of layout guide objects owned by this view.
var layoutMarginsGuide: UILayoutGuide
A layout guide representing the view’s margins.
var readableContentGuide: UILayoutGuide
A layout guide representing an area with a readable width within the view.
func removeLayoutGuide(UILayoutGuide)
Removes the specified layout guide from the view.
Measuring in Auto Layout
Returns the optimal size of the view based on its current constraints.
Returns the optimal size of the view based on its constraints and the specified fitting priorities.
var intrinsicContentSize: CGSize
The natural size for the receiving view, considering only properties of the view itself.
func invalidateIntrinsicContentSize()
Invalidates the view’s intrinsic content size.
Returns the priority with which a view resists being made smaller than its intrinsic size.
func setContentCompressionResistancePriority(UILayoutPriority, for: NSLayoutConstraint.Axis)
Sets the priority with which a view resists being made smaller than its intrinsic size.
Returns the priority with which a view resists being made larger than its intrinsic size.
func setContentHuggingPriority(UILayoutPriority, for: NSLayoutConstraint.Axis)
Sets the priority with which a view resists being made larger than its intrinsic size.
Aligning views in Auto Layout
Returns the view’s alignment rectangle for a given frame.
Returns the view’s frame for a given alignment rectangle.
var alignmentRectInsets: UIEdgeInsets
The insets from the view’s frame that define its alignment rectangle.
var forFirstBaselineLayout: UIView
Returns a view used to satisfy first baseline constraints.
var forLastBaselineLayout: UIView
Returns a view used to satisfy last baseline constraints.
Triggering Auto Layout
A Boolean value that determines whether the view’s constraints need updating.
func setNeedsUpdateConstraints()
Controls whether the view’s constraints need updating.
func updateConstraints()
Updates constraints for the view.
func updateConstraintsIfNeeded()
Updates the constraints for the receiving view and its subviews.
Debugging Auto Layout
Returns the constraints impacting the layout of the view for a given axis.
var hasAmbiguousLayout: Bool
A Boolean value that determines whether the constraints impacting the layout of the view incompletely specify the location of the view.
func exerciseAmbiguityInLayout()
Randomly changes the frame of a view with an ambiguous layout between the different valid values.
Configuring the resizing behavior
Define how a view adjusts its content when its bounds change.
var contentMode: UIView.ContentMode
A flag used to determine how a view lays out its content when its bounds change.
enum ContentMode
Options to specify how a view adjusts its content when its size changes.
Asks the view to calculate and return the size that best fits the specified size.
func sizeToFit()
Resizes and moves the receiver view so it just encloses its subviews.
var autoresizesSubviews: Bool
A Boolean value that determines whether the receiver automatically resizes its subviews when its bounds change.
var autoresizingMask: UIView.AutoresizingMask
An integer bit mask that determines how the receiver resizes itself when its superview’s bounds change.
Laying out subviews
Lay out views manually if your app doesn’t use Auto Layout.
func layoutSubviews()
Lays out subviews.
func setNeedsLayout()
Invalidates the current layout of the receiver and triggers a layout update during the next update cycle.
func layoutIfNeeded()
Lays out the subviews immediately, if layout updates are pending.
class var requiresConstraintBasedLayout: Bool
A Boolean value that indicates whether the receiver depends on the constraint-based layout system.
var translatesAutoresizingMaskIntoConstraints: Bool
A Boolean value that determines whether the view’s autoresizing mask is translated into Auto Layout constraints.
Accessing insets and layout guides
struct LayoutRegion
Adjusting the user interface
var overrideUserInterfaceStyle: UIUserInterfaceStyle
The user interface style adopted by the view and all of its subviews.
var semanticContentAttribute: UISemanticContentAttribute
A semantic description of the view’s contents, used to determine whether the view should be flipped when switching between left-to-right and right-to-left layouts.
var effectiveUserInterfaceLayoutDirection: UIUserInterfaceLayoutDirection
The user interface layout direction appropriate for arranging the immediate content of the view.
Returns the user interface direction for the given semantic content attribute.
Returns the layout direction implied by the specified semantic content attribute, relative to the specified layout direction.
Constraining views to the keyboard
var keyboardLayoutGuide: UIKeyboardLayoutGuide
A layout guide that tracks the keyboard’s position in your app’s layout.
Adding and removing interactions
func addInteraction(any UIInteraction)
Adds an interaction to the view.
func removeInteraction(any UIInteraction)
Removes an interaction from the view.
var interactions: [any UIInteraction]
The array of interactions for the view.
protocol UIInteraction
The protocol that an interaction implements to access the view that owns it.
Drawing and updating the view
func draw(CGRect)
Draws the view’s image within the passed-in rectangle.
func setNeedsDisplay()
Marks the receiver’s entire bounds rectangle as needing to be redrawn.
func setNeedsDisplay(CGRect)
Marks the specified rectangle of the receiver as needing to be redrawn.
var contentScaleFactor: CGFloat
The scale factor applied to the view.
func tintColorDidChange()
Called by the system when the tint color property changes.
Updating the view when property values change
struct Invalidating
A property wrapper that notifies the system that a property value change has invalidated an aspect of the containing view.
protocol UIViewInvalidating
Implements a type of invalidation that can occur on a view that requires an update.
Formatting printed view content
Returns a print formatter for the receiving view.
func draw(CGRect, for: UIViewPrintFormatter)
Implemented to draw the view’s content for printing.
Managing gesture recognizers
func addGestureRecognizer(UIGestureRecognizer)
Attaches a gesture recognizer to the view.
func removeGestureRecognizer(UIGestureRecognizer)
Detaches a gesture recognizer from the receiving view.
var gestureRecognizers: [UIGestureRecognizer]?
The gesture-recognizer objects currently attached to the view.
Asks the view if the gesture recognizer should continue tracking touch events.
Working with focus
var canBecomeFocused: Bool
A Boolean value that indicates whether the view is currently capable of being focused.
class var inheritedAnimationDuration: TimeInterval
Returns the inherited duration of the current animation.
var isFocused: Bool
A Boolean value that indicates whether the item is currently focused.
var focusGroupIdentifier: String?
The identifier of the focus group that this view belongs to.
var focusEffect: UIFocusEffect?
The visual effect to apply when the view becomes focused.
var focusGroupPriority: UIFocusGroupPriority
The importance of the item within a focus group, used by the focus system to determine the group’s primary item.
Using motion effects
func addMotionEffect(UIMotionEffect)
Begins applying a motion effect to the view.
var motionEffects: [UIMotionEffect]
The array of motion effects for the view.
func removeMotionEffect(UIMotionEffect)
Stops applying a motion effect to the view.
Managing the hover appearance
var hoverStyle: UIHoverStyle?
The hover style for the view.
class UIHoverStyle
The hover style to apply to a view, including an effect and a shape to use for displaying that effect.
class UIHoverEffectLayer
Managing font-sizing preferences
var minimumContentSizeCategory: UIContentSizeCategory?
The minimum content size category for the view and its subviews.
var maximumContentSizeCategory: UIContentSizeCategory?
The maximum content size category for the view and its subviews.
var appliedContentSizeCategoryLimitsDescription: String
A string that lists each of the view’s superviews, its content size category, and whether that view has content size category limits.
Preserving and restoring state
var restorationIdentifier: String?
The identifier that determines whether the view supports state restoration.
func encodeRestorableState(with: NSCoder)
Encodes state-related information for the view.
func decodeRestorableState(with: NSCoder)
Decodes and restores state-related information for the view.
Capturing a view snapshot
Returns a snapshot view based on the contents of the current view.
Returns a snapshot view based on the specified contents of the current view, with stretchable insets.
Renders a snapshot of the complete view hierarchy as visible onscreen into the current context.
Identifying the view at runtime
var tag: Int
An integer that you can use to identify view objects in your application.
Returns the view whose tag matches the specified value.
Converting between view coordinate systems
Converts a point from the receiver’s coordinate system to that of the specified view.
Converts a point from the coordinate system of a given view to that of the receiver.
Converts a rectangle from the receiver’s coordinate system to that of another view.
Converts a rectangle from the coordinate system of another view to that of the receiver.
Hit-testing in a view
Returns the farthest descendant in the view hierarchy of the current view, including itself, that contains the specified point.
Returns a Boolean value indicating whether the receiver contains the specified point.
Ending a view-editing session
Causes the view (or one of its embedded text fields) to resign the first responder status.
Modifying the accessibility behavior
var accessibilityIgnoresInvertColors: Bool
A Boolean value indicating whether the view ignores an accessibility request to invert its colors.
var largeContentImage: UIImage?
An image that represents the view in the large content viewer.
var largeContentImageInsets: UIEdgeInsets
Insets to adjust the position of the view’s image so it appears centered in the large content viewer.
var largeContentTitle: String?
A string that describes the view in the large content viewer.
var scalesLargeContentImage: Bool
A Boolean value that indicates whether the large content viewer scales the item’s image to a larger size.
var showsLargeContentViewer: Bool
A Boolean value that indicates whether to show the view in the large content viewer.
Animating views
Animates changes to one or more views using a spring animation with the specified duration, bounce, initial velocity, delay, options, and completion handler.
Animate changes to one or more views using the specified duration, delay, options, and completion handler.
Animate changes to one or more views using the specified duration and completion handler.
Animate changes to one or more views using the specified duration.
Creates a transition animation for the specified container view.
Creates a transition animation between the specified views using the given parameters.
Creates an animation block object that can be used to set up keyframe-based animations for the current view.
Specifies the timing and animation values for a single frame of a keyframe animation.
Performs a specified system-provided animation on one or more views, along with optional parallel animations that you define.
Performs a view animation using a timing curve corresponding to the motion of a physical spring.
Disables a view transition animation.
Repeats the specified animations a specific number of times, optionally running the animation forward and backward.
Constants
enum AnimationCurve
Specifies the supported animation curves.
struct AnimationOptions
Options for animating views using block objects.
enum AnimationTransition
Animation transition options for use in an animation block object.
enum SystemAnimation
Option to remove the views from the hierarchy when animation is complete.
struct KeyframeAnimationOptions
Options for configuring keyframe-based animations.
enum Axis
Keys that specify a horizontal or vertical layout constraint between objects.
enum TintAdjustmentMode
The tint adjustment mode for the view.
class let layoutFittingCompressedSize: CGSize
The option to use the smallest possible size.
class let layoutFittingExpandedSize: CGSize
The option to use the largest possible size.
class let noIntrinsicMetric: CGFloat
The absence of an intrinsic metric for a given numeric view property.
struct AutoresizingMask
Options for automatic view resizing.
enum UISemanticContentAttribute
Deprecated
Symbols that views no longer support.
Initializers
convenience init()
Instance Methods
func setNeedsUpdateProperties()
Call to manually request a properties update for the view. Multiple requests may be coalesced into a single update alongside the next layout pass.
Beta
func updateProperties()
Override point for subclasses to update properties of this view. Never call this method directly; use setNeedsUpdateProperties to schedule an update.
func updatePropertiesIfNeeded()
Forces an immediate properties update for this view (and its view controller, if applicable) and any subviews, including any view controllers or views in its subtree.
Enumerations
enum Invalidations
Changes that cause an aspect of a view to be invalid and require an update.
Relationships
Inherits From
UIResponder
Inherited By
UIActionSheetUIActivityIndicatorViewUIAlertViewUIBackgroundExtensionViewUICalendarViewUICollectionReusableViewUIContentUnavailableViewUIControlUIEventAttributionViewUIImageViewUIInputViewUILabelUIListContentViewUINavigationBarUIPickerViewUIPopoverBackgroundViewUIProgressViewUIScrollViewUISearchBarUIStackViewUIStandardTextCursorViewUITabBarUITableViewCellUITableViewHeaderFooterViewUIToolbarUIVisualEffectViewUIWebViewUIWindow
Conforms To
CALayerDelegateCVarArgCopyableCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
View fundamentals
UIKit Catalog: Creating and customizing views and controls
Customize your app’s user interface with views and controls.
https://developer.apple.com/documentation/uikit/uiapplication
- UIKit
- UIApplication
Class
UIApplication
The centralized point of control and coordination for apps running in iOS.
tvOS
@MainActor class UIApplication
Mentioned in
Using responders and the responder chain to handle events
About the app launch sequence
About App Development with UIKit
Handling key presses made on a physical keyboard
About the UI preservation process
Overview
Every iOS app has exactly one instance of UIApplication (or, very rarely, a subclass of UIApplication). When an app launches, the system calls the UIApplicationMain(_:_:_:_:) function. Among its other tasks, this function creates a singleton UIApplication object that you access using shared.
Your app’s application object handles the initial routing of incoming user events. It dispatches action messages forwarded to it by control objects (instances of the UIControl class) to appropriate target objects. The application object maintains a list of open windows ( UIWindow objects), which it can use to retrieve any of the app’s UIView objects.
The UIApplication class defines a delegate that conforms to the UIApplicationDelegate protocol and must implement some of the protocol’s methods. The application object informs the delegate of significant runtime events—for example, app launch, low-memory warnings, and app termination—giving it an opportunity to respond appropriately.
Apps can cooperatively handle a resource, such as an email or an image file, through the open(_:options:completionHandler:) method. For example, an app that calls this method with an email URL causes the Mail app to launch and display the message.
The APIs in this class allow you to manage device-specific behavior. Use your UIApplication object to do the following:
-
Temporarily suspend incoming touch events (
beginIgnoringInteractionEvents()) -
Register for remote notifications (
registerForRemoteNotifications()) -
Trigger the undo-redo UI (
applicationSupportsShakeToEdit) -
Determine whether there is an installed app registered to handle a URL scheme (
canOpenURL(_:)) -
Extend the execution of the app so that it can finish a task in the background (
beginBackgroundTask(expirationHandler:)andbeginBackgroundTask(withName:expirationHandler:)) -
Schedule and cancel local notifications (
scheduleLocalNotification(_:)andcancelLocalNotification(_:)) -
Coordinate the reception of remote-control events (
beginReceivingRemoteControlEvents()andendReceivingRemoteControlEvents()) -
Perform app-level state restoration tasks (methods in the Managing state restoration task group)
Subclassing notes
Most apps don’t need to subclass UIApplication. Instead, use an app delegate to manage interactions between the system and the app.
If your app must handle incoming events before the system does—a very rare situation—you can implement a custom event or action dispatching mechanism. To do this, subclass UIApplication and override the sendEvent(_:) and/or the sendAction(_:to:from:for:) methods. For every event you intercept, after you handle the event, dispatch it
Accessing the shared application
class var shared: UIApplication
The singleton app instance.
Configuring your app’s behavior
var delegate: (any UIApplicationDelegate)?
The delegate of the app object.
protocol UIApplicationDelegate
A set of methods to manage shared behaviors for your app.
Registering for remote notifications
func registerForRemoteNotifications()
Registers to receive remote notifications through Apple Push Notification service.
func unregisterForRemoteNotifications()
Unregisters for all remote notifications received through Apple Push Notification service.
var isRegisteredForRemoteNotifications: Bool
A Boolean value that indicates whether the app is currently registered for remote notifications.
Getting the application state
var applicationState: UIApplication.State
The app’s current state, or that of its most active scene.
enum State
Constants that indicate the running states of an app.
Getting scene information
var supportsMultipleScenes: Bool
A Boolean value that indicates whether the app may display multiple scenes simultaneously.
The app’s currently connected scenes.
The sessions whose scenes are either currently active or archived by the system.
Managing a scene’s life cycle
Asks the system to activate an existing scene or create a new scene and associate it with your app.
Asks the system to dismiss an existing scene and remove it from the app switcher.
func requestSceneSessionRefresh(UISceneSession)
Asks the system to update any system UI associated with the specified scene.
struct UISceneSessionActivationRequest
A collection of properties that you use to request activation of a scene.
class ActivationRequestOptions
An object that contains information you want the system to use when activating the session associated with a scene.
class UISceneDestructionRequestOptions
An object you pass to UIKit to permanently remove a scene and its associated session from your app.
Managing background tasks
var backgroundRefreshStatus: UIBackgroundRefreshStatus
Indicates whether the app can refresh content when running in the background.
enum UIBackgroundRefreshStatus
Constants that indicate whether background execution is enabled for the app.
class let backgroundRefreshStatusDidChangeNotification: NSNotification.Name
A notification that posts when the app’s status for downloading content in the background changes.
Marks the start of a task with a custom name that should continue if the app enters the background.
Marks the start of a task that should continue if the app enters the background.
func endBackgroundTask(UIBackgroundTaskIdentifier)
Marks the end of a specific long-running background task.
struct UIBackgroundTaskIdentifier
A unique token that identifies a request to run in the background.
var backgroundTimeRemaining: TimeInterval
The maximum amount of time remaining for the app to run in the background.
Fetching content in the background
class let backgroundFetchIntervalMinimum: TimeInterval
The smallest fetch interval supported by the system.
class let backgroundFetchIntervalNever: TimeInterval
A fetch interval large enough to prevent fetch operations from occurring.
Opening a URL resource
Attempts to asynchronously open the resource at the specified URL.
Returns a Boolean value that indicates whether an app is available to handle a URL scheme.
struct OpenExternalURLOptionsKey
Options for opening a URL.
Deep linking to custom settings
class let openSettingsURLString: String
The URL string you use to deep link to your app’s custom settings in the Settings app.
static let openNotificationSettingsURLString: String
The URL string you use to deep link to your app’s notification settings in the Settings app.
let UIApplicationOpenNotificationSettingsURLString: String
A constant that provides the URL string you use to deep link to your app’s notification settings in the Settings app.
Deprecated
class let openDefaultApplicationsSettingsURLString: String
The URL string used to select a default app in the Settings app.
Managing the app’s idle timer
var isIdleTimerDisabled: Bool
A Boolean value that controls whether the idle timer is disabled for the app.
Managing state restoration
func extendStateRestoration()
Tells the app that your code is restoring state asynchronously.
func completeStateRestoration()
Tells the app that your code has finished any asynchronous state restoration.
func ignoreSnapshotOnNextApplicationLaunch()
Prevents the app from using the recent snapshot image during the next launch cycle.
class func registerObject(forStateRestoration: any UIStateRestoring, restorationIdentifier: String)
Registers a custom object for use with the state restoration system.
Providing an app’s shortcut items
var shortcutItems: [UIApplicationShortcutItem]?
The Home screen dynamic quick actions for your app; available on devices that support 3D Touch.
Accessing protected content
var isProtectedDataAvailable: Bool
A Boolean value that indicates whether content protection is active.
class let protectedDataDidBecomeAvailableNotification: NSNotification.Name
A notification that posts when the protected files become available for your code to access.
class let protectedDataWillBecomeUnavailableNotification: NSNotification.Name
A notification that posts shortly before protected files are locked down and become inaccessible.
Receiving remote control events
func beginReceivingRemoteControlEvents()
Tells the app to begin receiving remote-control events.
func endReceivingRemoteControlEvents()
Tells the app to stop receiving remote-control events.
Accessing the layout direction
var userInterfaceLayoutDirection: UIUserInterfaceLayoutDirection
The layout direction of the user interface.
enum UIUserInterfaceLayoutDirection
Constants that specify the directional flow of the user interface.
Controlling and handling events
func sendEvent(UIEvent)
Dispatches an event to the appropriate responder objects in the app.
Sends an action message identified by the selector to a specified target.
var applicationSupportsShakeToEdit: Bool
A Boolean value that determines whether shaking the device displays the undo-redo user interface.
Managing the app’s icon
var supportsAlternateIcons: Bool
A Boolean value that indicates whether the app is allowed to change its icon.
var alternateIconName: String?
The name of the icon the system displays for the app.
Changes the icon the system displays for the app.
Managing the preferred content size
var preferredContentSizeCategory: UIContentSizeCategory
The font sizing option preferred by the user.
struct UIContentSizeCategory
Constants that indicate the preferred size of your content.
protocol UIContentSizeCategoryAdjusting
A collection of methods that give controls an easy way to adopt automatic adjustment to content category changes.
static let didChangeNotification: NSNotification.Name
A notification that posts when the user changes the preferred content size setting.
static let newValueUserInfoKey: String
A key that reflects the new preferred content size.
Specifying the supported interface orientations
Returns the default set of interface orientations to use for the view controllers in the specified window.
Tracking controls in the run loop
static let tracking: RunLoop.Mode
The mode set while tracking in controls takes place.
Detecting screenshots
class let userDidTakeScreenshotNotification: NSNotification.Name
A notification that posts when a person takes a screenshot on the device.
Discovering if your app is the default app in a category
Reports whether this app is the person’s default app in the given category.
enum Category
Constants that describe the types of apps in the system.
struct CategoryDefaultError
Errors that can happen when the system checks if your app is the default app in a category.
Deprecated
Review unsupported symbols and their replacements.
Structures
struct BackgroundRefreshStatusDidChangeMessage Beta
struct DidBecomeActiveMessage Beta
struct DidEnterBackgroundMessage Beta
struct DidFinishLaunchingMessage Beta
struct DidReceiveMemoryWarningMessage Beta
struct ProtectedDataDidBecomeAvailableMessage Beta
struct ProtectedDataWillBecomeUnavailableMessage Beta
struct SignificantTimeChangeMessage Beta
struct UserDidTakeScreenshotMessage Beta
struct WillEnterForegroundMessage Beta
struct WillResignActiveMessage Beta
struct WillTerminateMessage Beta
Relationships
Inherits From
UIResponder
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIActivityItemsConfigurationProvidingUIPasteConfigurationSupportingUIResponderStandardEditActionsUIUserActivityRestoring
See Also
Life cycle
Respond to system notifications when your app is in the foreground or background, and handle other significant system-related events.
Initialize your app’s data structures, prepare your app to run, and respond to any launch-time requests from the system.
Manage multiple instances of your app’s UI simultaneously, and direct resources to the appropriate instance of your UI.
https://developer.apple.com/documentation/uikit/uidocument)
https://developer.apple.com/documentation/uikit/uiview)
https://developer.apple.com/documentation/uikit/uiapplication)
https://developer.apple.com/documentation/uikit/creating-a-mac-version-of-your-ipad-app
- UIKit
- Mac Catalyst
- Creating a Mac version of your iPad app
Article
Creating a Mac version of your iPad app
Bring your iPad app to macOS with Mac Catalyst.
Overview
With Xcode 11 and later, you can create a Mac version of your iPad app using Mac Catalyst. Configuring your app for Mac can take just a click in a checkbox, although you may need more steps, depending on the features and frameworks that your app uses.
Configure your app for Mac
To add support for Mac, open your Xcode project and select the iOS target that you want to configure. In the General tab, under Deployment Info, select the Mac checkbox. (If your app supports iPhone only, the checkbox is unavailable.)
When you enable Mac support, Xcode adds the App Sandbox Entitlement to your project. Xcode only includes this entitlement in the Mac version of your app, not the iOS version. Xcode also adds My Mac to the list of destinations. Select this destination to run your Mac app from Xcode.
At this point, you may be able to build and run the Mac version of your app. To give it a try, select My Mac as the destination and run your project.
Go beyond the checkbox
You may find that the Mac version of your app still doesn’t build because:
-
Your project includes incompatible frameworks, libraries, or embedded content.
-
Your source code references unsupported APIs.
When you enable Mac support, Xcode automatically excludes incompatible frameworks and embedded content where possible for Mac builds of your project. Still, you may need to manually exclude other frameworks or content.
To manually exclude an item, open Frameworks, Libraries, and Embedded Content under the General tab for your iOS target. Then select iOS as the platform setting for the item. This setting excludes the item from the Mac version of your app.
If you have source code referencing APIs unavailable to the Mac version of your app, enclose the code in a compilation conditional block that uses the targetEnvironment() (Swift) or TARGET_OS_MACCATALYST (Objective-C) platform condition.
#if !targetEnvironment(macCatalyst) // Code to exclude from Mac. #endif
#if !TARGET_OS_MACCATALYST #endif
You can use these same approaches to include a framework and code that are available only in macOS. For a framework, select macOS for the platform setting, and enclose the code with a #if targetEnvironment(macCatalyst) (Swift) or #if TARGET_OS_MACCATALYST (Objective-C) statement.
Make your app more like a Mac app
After following these steps, you should be able to run your iPad app on Mac. But before you ship your new app to customers, it needs a few more changes to make it more like a Mac app. To learn more, see Optimizing your iPad app for Mac.
https://developer.apple.com/documentation/uikit/choosing-a-user-interface-idiom-for-your-mac-app
https://developer.apple.com/documentation/uikit/optimizing-your-ipad-app-for-mac
https://developer.apple.com/documentation/uikit/uikit-catalog-creating-and-customizing-views-and-controls
https://developer.apple.com/documentation/uikit/building-and-improving-your-app-with-mac-catalyst
- UIKit
- Mac Catalyst
- Building and improving your app with Mac Catalyst
Sample Code
Building and improving your app with Mac Catalyst
Improve your iPadOS app with Mac Catalyst by supporting native controls, multiple windows, sharing, printing, menus and keyboard shortcuts.
Download
Xcode 13.0+
Overview
See Also
User interface
UIKit Catalog: Creating and customizing views and controls
Customize your app’s user interface with views and controls.
Displaying a checkbox in your Mac app built with Mac Catalyst
Present a switch control as a Mac-style checkbox when your app runs in the Mac user interface idiom.
Removing the title bar in your Mac app built with Mac Catalyst
Display content that fills the entire height of a window by removing the title bar.
Provide a space for controls under a window’s title bar and above your custom content.
Touch Bar
Display interactive content and controls in the Touch Bar.
https://developer.apple.com/documentation/uikit/displaying-a-checkbox-in-your-mac-app-built-with-mac-catalyst
- UIKit
- Mac Catalyst
- Displaying a checkbox in your Mac app built with Mac Catalyst
Article
Displaying a checkbox in your Mac app built with Mac Catalyst
Present a switch control as a Mac-style checkbox when your app runs in the Mac user interface idiom.
Overview
A Mac app built with Mac Catalyst that uses the Mac user interface idiom displays a UISwitch as a checkbox when the preferredStyle value is UISwitch.Style.automatic (the default value) or UISwitch.Style.checkbox. If your app doesn’t use the UIUserInterfaceIdiom.mac idiom, the switch appears as a slider switch. To learn more, see Choosing a user interface idiom for your Mac app.
Add text to the checkbox
To display text alongside the checkbox, set the title property.
let showFavoritesAtTop = UISwitch() showFavoritesAtTop.title = "Always show favorite recipes at the top"
Resize the checkbox
A checkbox-style switch has a default frame size of zero. If you’re not using Auto Layout to determine the size and position of the switch, call sizeToFit() to resize it so that it uses the appropriate amount of space needed to display the checkbox and its title.
See Also
User interface
UIKit Catalog: Creating and customizing views and controls
Customize your app’s user interface with views and controls.
Building and improving your app with Mac Catalyst
Improve your iPadOS app with Mac Catalyst by supporting native controls, multiple windows, sharing, printing, menus and keyboard shortcuts.
Removing the title bar in your Mac app built with Mac Catalyst
Display content that fills the entire height of a window by removing the title bar.
Provide a space for controls under a window’s title bar and above your custom content.
Touch Bar
Display interactive content and controls in the Touch Bar.
https://developer.apple.com/documentation/uikit/removing-the-title-bar-in-your-mac-app-built-with-mac-catalyst
- UIKit
- Mac Catalyst
- Removing the title bar in your Mac app built with Mac Catalyst
Article
Removing the title bar in your Mac app built with Mac Catalyst
Display content that fills the entire height of a window by removing the title bar.
Overview
By default, Mac apps built with Mac Catalyst display a title bar across the top of their windows. A horizontal line separates the title bar from the content of the window.
Some Mac apps such as Messages and Contacts have no title bar in their main window. Instead, the top of the window shows only the Close, Minimize, and Zoom buttons with no separator between them and the window’s content. In this UI design, the content area fills the entire height of the window.
The following image illustrates these styles in two windows. The first window displays a title bar, while the second has none.
Remove the title bar
If you choose to design your window without a title bar, you must remove it from the window. To remove the title bar, set the title bar’s titleVisibility property to UITitlebarTitleVisibility.hidden and the toolbar property to nil. The following code shows how to remove the title bar and its separator from the window during the setup of a new scene.
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
#if targetEnvironment(macCatalyst) if let titlebar = windowScene.titlebar { titlebar.titleVisibility = .hidden titlebar.toolbar = nil } #endif
}
See Also
User interface
UIKit Catalog: Creating and customizing views and controls
Customize your app’s user interface with views and controls.
Building and improving your app with Mac Catalyst
Improve your iPadOS app with Mac Catalyst by supporting native controls, multiple windows, sharing, printing, menus and keyboard shortcuts.
Displaying a checkbox in your Mac app built with Mac Catalyst
Present a switch control as a Mac-style checkbox when your app runs in the Mac user interface idiom.
Provide a space for controls under a window’s title bar and above your custom content.
Touch Bar
Display interactive content and controls in the Touch Bar.
https://developer.apple.com/documentation/uikit/toolbar
Collection
- UIKit
- Mac Catalyst
- Toolbar
API Collection
Toolbar
Provide a space for controls under a window’s title bar and above your custom content.
Topics
View
Integrating a Toolbar and Touch Bar into Your App
Provide users quick access to your app’s features from a toolbar and corresponding Touch Bar.
@MainActor class NSToolbar
An object that manages the space above your app’s custom content and either below or integrated with the window’s title bar.
protocol NSToolbarItemValidation : NSObjectProtocol
Validation of a toolbar item.
Items
@MainActor class NSToolbarItem
A single item that appears in a window’s toolbar.
@MainActor class NSToolbarItemGroup
A group of subitems in a toolbar item.
enum ControlRepresentation
enum SelectionMode
A value that indicates how a grouped toolbar item selects its subitems.
@MainActor class NSMenuToolbarItem
A control that presents a menu in a window’s toolbar.
@MainActor class NSSearchToolbarItem
A toolbar item that contains a search field optimized for performing text-based searches.
@MainActor class NSTrackingSeparatorToolbarItem
A toolbar separator that aligns with the vertical split view in the same window.
class NSUIViewToolbarItem
An item in a window’s toolbar that hosts a custom UIKit view.
Item validation
protocol NSCloudSharingValidation : NSObjectProtocol
A protocol that a Cloud-sharing toolbar item uses to get validation of an item.
See Also
User interface
UIKit Catalog: Creating and customizing views and controls
Customize your app’s user interface with views and controls.
Building and improving your app with Mac Catalyst
Improve your iPadOS app with Mac Catalyst by supporting native controls, multiple windows, sharing, printing, menus and keyboard shortcuts.
Displaying a checkbox in your Mac app built with Mac Catalyst
Present a switch control as a Mac-style checkbox when your app runs in the Mac user interface idiom.
Removing the title bar in your Mac app built with Mac Catalyst
Display content that fills the entire height of a window by removing the title bar.
Touch Bar
Display interactive content and controls in the Touch Bar.
https://developer.apple.com/documentation/uikit/navigating-an-app-s-user-interface-using-a-keyboard
- UIKit
- Focus-based navigation
- Navigating an app’s user interface using a keyboard
Sample Code
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
Download
Xcode 13.0+
Overview
See Also
Focus interactions
About focus interactions for Apple TV
Design and implement intuitive control schemes for menus and interactive user interface layouts.
Adding user-focusable elements to a tvOS app
Create intuitive and easily manipulated user-interactive controls for your tvOS app.
protocol UIFocusEnvironment
A set of methods that define the focus behavior for a branch of the view hierarchy.
class UIFocusSystem
Queries and reevaluates the currently focused item.
class UIFocusUpdateContext
An object that provides information relevant to a specific focus update from one view to another.
protocol UIFocusItem
An object that can become focused.
class UIFocusMovementHint
Provides movement hint information for the focused item.
protocol UIFocusItemContainer
The container responsible for providing geometric context to focus items within a given focus environment.
protocol UIFocusItemScrollableContainer
A type of focus item container that supports automatic scrolling of focusable content.
struct UIFocusGroupPriority
The importance of an item within a focus group, used by the focus system to determine the group’s primary item.
https://developer.apple.com/documentation/uikit/adding-menus-and-shortcuts-to-the-menu-bar-and-user-interface
- UIKit
- Mac Catalyst
- Adding menus and shortcuts to the menu bar and user interface
Sample Code
Adding menus and shortcuts to the menu bar and user interface
Provide quick access to useful actions by adding menus and keyboard shortcuts to your Mac app built with Mac Catalyst.
Download
Xcode 13.1+
Overview
This sample project demonstrates how to add menu commands and keyboard shortcuts to the menu bar. The sample app uses its MenuController object to insert a UIMenuSystem object that adds the following menus:
-
New: Appears at the beginning of the File menu and contains the two operations New Date Item and New Text Item, which add items to the table view.
-
Cities: Contains a group of UICommand and UIKeyCommand objects.
-
Navigation: Contains a group of UIKeyCommand objects for command-key navigation.
-
Style: Contains a group of UICommand objects that have checkmark states. This grouping looks like a font-style menu for text formatting.
-
Tools: Contains a group of UICommand objects.
The sample project also shows you how to add contextual menus to views, and how to handle menu-command selection using UIContextMenuInteractionDelegate.
Configure the sample code project
In Xcode, select your development team on the iOS target’s Signing and Capabilities tab.
Add menus to the menu bar
Create UIMenu objects and use them to construct the menus and submenus. This sample adds menus to the menu bar when it runs on macOS, and key command elements in those menus also appear in the discoverability heads-up display (HUD) on iPad when the user presses the command key.
The Mac version of an iPad app comes with a standard menu bar. Use the UIMenuSystem class, an object that represents the main or contextual menu system, to modify the menu bar.
The sample uses UIMenuSystem to add menus and key commands to the main system menu by implementing buildMenu(with:) in AppDelegate. This function receives a UIMenuBuilder object that the sample then uses to add and remove menus. Because menus can exist with no window or view hierarchy, the system only consults UIApplication and UIApplicationDelegate to build the app’s menu bar.
Menu commands consist of UICommand, UIKeyCommand, and UIAction objects that are grouped in a UIMenu container.
Add menu commands to the file menu
This sample inserts a UIKeyCommand called Command-O into the File Menu and creates a corresponding keyboard shortcut:
let openCommand = UIKeyCommand(title: NSLocalizedString("OpenTitle", comment: ""), image: nil, action: #selector(AppDelegate.openAction), input: "o", modifierFlags: .command) let openMenu = UIMenu(title: "", image: nil, identifier: .openMenu, options: .displayInline, children: [openCommand]) return openMenu }
Notice that the UIKeyCommand title is a localized string using the NSLocalizedString function, which can display the menu name in multiple languages.
This sample inserts the Open command into the middle of the menu bar’s File menu:
builder.insertChild(MenuController.openMenu(), atStartOfMenu: .file)
Mac apps also typically include a Print menu command in the File menu. This sample includes both Print and Export as PDF menu commands in the File Menu. These menu commands are automatically inserted when the Info.plist contains the UIApplicationSupportsPrintCommand key whose value is set to true. The application responds to these print commands by implementing UIResponder's printContent(_ sender: Any?) function.
Contribute to the edit menu
Editing operations, such as cut, copy, paste, and delete, are commonly used in most apps. This sample app provides these operations through the Edit menu, where the user can edit the sample’s left-side content or its primary table-view content. These operations represent the first-responder functions cut(_ sender: Any?), copy(_ sender: Any?), paste(_ sender: Any?), delete(_ sender: Any?).
This sample implements canPerformAction:withSender: to determine if these edit operations are supported.
if action == #selector(printContent) { // Allow for printing if a table view cell is selected. return tableView.indexPathForSelectedRow != nil } else if action == #selector(newAction(_:)) { // User wants to perform a New operation. return true } else { switch (tableView.indexPathForSelectedRow, action) {
// These Edit commands are supported. case let (?, action) where action == #selector(cut(:)) || action == #selector(copy(:)) || action == #selector(delete(:)): return true case (_?, _): // Allow the nextResponder to make the determination. return super.canPerformAction(action, withSender: sender)
// Paste is supported if the pasteboard has text. case (.none, action) where action == #selector(paste(_:)): return (UIPasteboard.general.string != nil) ? true : // Allow the nextResponder to make the determination. super.canPerformAction(action, withSender: sender) case (.none, _): return false } } }
Add commands to control the user interface
In the sample, you can change the primary or left-side table view’s selection by using UIKeyCommand. These key commands are connected to the up and down arrow keys and are added directly to the table view. The following example shows how to add the down arrow key as a UIKeyCommand:
let downArrowCommand = UIKeyCommand(input: UIKeyCommand.inputDownArrow, modifierFlags: [], action: #selector(PrimaryViewController.downArrowAction(_:))) addKeyCommand(downArrowCommand)
The sample also demonstrates how to add menu commands as command-key equivalents. The following example shows how to create a menu with all four arrow keys as command keys:
let keyCommands = [ UIKeyCommand.inputRightArrow,
UIKeyCommand.inputLeftArrow,
UIKeyCommand.inputUpArrow,
UIKeyCommand.inputDownArrow ]
let arrows = Arrows.allCases
let arrowKeyChildrenCommands = zip(keyCommands, arrows).map { (command, arrow) in UIKeyCommand(title: arrow.localizedString(), image: nil, action: #selector(AppDelegate.navigationMenuAction(_:)), input: command, modifierFlags: .command, propertyList: [CommandPListKeys.ArrowsKeyIdentifier: arrow.rawValue]) }
let arrowKeysGroup = UIMenu(title: "", image: nil, identifier: .arrowsMenu, options: .displayInline, children: arrowKeyChildrenCommands)
return UIMenu(title: NSLocalizedString("NavigationTitle", comment: ""), image: nil, identifier: .navMenu, options: [], children: [arrowKeysGroup]) }
Display contextual menus
The sample displays a contextual menu through the use of UIContextMenuInteractionDelegate, an interaction object used to display relevant actions for the content.
For macOS, the user control-clicks or right-clicks the DetailViewController. For iPadOS, the user taps and holds the DetailViewController. The sample uses UIContextMenuInteractionDelegate to display Cut, Copy, Paste, Delete, Rename, and Share commands. This kind of contextual menu is a grouping of UIAction objects. UIAction is a menu element that performs its action in a closure. In iOS, optionally customize this contextual menu’s highlight preview by using contextMenuInteraction(_:previewForHighlightingMenuWithConfiguration:). This delegate function returns a primary view controller. Override this function to enable menu commands based on the table view state or the state of the pasteboard.
Adjust the style menu
The sample implements validate(_:), where it can adjust the Style menu as the user selects between one or more font styles: plain, bold, italic, underline.
// The font style menu item check marks used in the Style menu.
// Update the state of a given command by adjusting the Style menu. // Note: Only command groups that are added will be called to validate. override func validate(_ command: UICommand) { // Obtain the plist of the incoming command.
if let fontStyleDict = command.propertyList as? [String: String] { // Check if the command comes from the Style menu. if let fontStyle = fontStyleDict[MenuController.CommandPListKeys.StylesIdentifierKey] { // Update the Style menu command state (checked or unchecked). command.state = fontMenuStyleStates.contains(fontStyle) ? .on : .off } } else { // Validate the disabled command. This keeps the menu item disabled. if let commandPlistString = command.propertyList as? String { if commandPlistString == MenuController.disabledCommand { command.attributes = .disabled } } } }
Add a preferences menu
Mac apps typically display app-specific preferences using a preferences window. The sample adds a preferences window by adding a Settings bundle to the Xcode project’s target. The window automatically becomes available to the user through the Preferences menu command in the Application menu. To learn more about preferences, see Displaying a Preferences window.
See Also
User interactions
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
Handling key presses made on a physical keyboard
Detect when someone presses and releases keys on a physical keyboard.
class UIHoverGestureRecognizer
A continuous gesture recognizer that interprets pointer movement over a view.
https://developer.apple.com/documentation/uikit/handling-key-presses-made-on-a-physical-keyboard
- UIKit
- Keyboards and input
- Handling key presses made on a physical keyboard
Article
Handling key presses made on a physical keyboard
Detect when someone presses and releases keys on a physical keyboard.
Overview
In iOS apps and Mac apps built with Mac Catalyst, the system reports key presses that a person makes on a physical keyboard by sending press events to responder objects in the responder chain of the active app.
A responder chain is a linked series of UIResponder objects, such as UIViewController and UIApplication, that either handle an event or transfer responsibility for handling the event to other responders in the app. To learn more about responders and the responder chain, see Using responders and the responder chain to handle events.
Detect a key press
To detect a key press that a person makes on a physical keyboard, override pressesBegan(_:with:) in a responder object of your app such as the app delegate or main view controller.
To determine what key they pressed, iterate through the set of presses, inspecting the key property of each press. Use charactersIgnoringModifiers to determine the text value of key, and whether the responder should handle the key press or not. If the responder doesn’t handle the key press, call pressesBegan(_:with:) on the superclass to send the press event to the next responder in the active responder chain.
For example, the following code listing handles someone pressing either the left or right arrow.
// Handle someone pressing a key on a physical keyboard.
with event: UIPressesEvent?) {
var didHandleEvent = false
for press in presses {
// Get the pressed key. guard let key = press.key else { continue }
if key.charactersIgnoringModifiers == UIKeyCommand.inputLeftArrow { // Someone pressed the left arrow key. // Respond to the key-press event. didHandleEvent = true } if key.charactersIgnoringModifiers == UIKeyCommand.inputRightArrow { // Someone pressed the right arrow key. // Respond to the key-press event. didHandleEvent = true } }
if didHandleEvent == false { // If someone presses a key that you're not handling, // pass the event to the next responder. super.pressesBegan(presses, with: event) } }
Detect a key release
Override the responder’s pressesEnded(_:with:) method to detect when someone releases a key. To get information about the key, do the same as you did when detecting a key press; inspect the key property of each press in the presses set. For example, the following code listing handles someone releasing either the left or right arrow.
// Handle someone releasing a key on a physical keyboard.
// Get the released key. guard let key = press.key else { continue }
if key.charactersIgnoringModifiers == UIKeyCommand.inputLeftArrow { // Someone released the left arrow key. // Respond to the event. didHandleEvent = true } if key.charactersIgnoringModifiers == UIKeyCommand.inputRightArrow { // Someone released the right arrow key. // Respond to the event. didHandleEvent = true } }
if didHandleEvent == false { // If someone releases a key that you're not handling, // pass the event to the next responder. super.pressesEnded(presses, with: event) } }
See Also
Physical keyboards
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
Adding hardware keyboard support to your app
Enhance interactions with your app by handling raw keyboard events, writing custom keyboard shortcuts, and working with gesture recognizers.
class UIKey
An object that provides information about the state of a keyboard key.
enum UIKeyboardHIDUsage
A set of HID usage codes that identify the keys of a USB keyboard.
https://developer.apple.com/documentation/uikit/uihovergesturerecognizer
- UIKit
- UIHoverGestureRecognizer
Class
UIHoverGestureRecognizer
A continuous gesture recognizer that interprets pointer movement over a view.
@MainActor class UIHoverGestureRecognizer
Mentioned in
Optimizing your iPad app for Mac
Overview
On macOS and iPadOS devices, a person can move the pointer over user interface elements. For some UI designs, it’s important to know when the pointer moves over an element, with no other user interactions, such as clicking the mouse button. The text for a hyperlink, for instance, may change colors or appear with an underline as the pointer moves over the link. This creates a rollover effect.
To provide this experience in your app, add a hover gesture recognizer that reacts as the pointer moves over the view. Provide the gesture recognizer with a target and action that the system calls when the pointer enters, exits, and moves across the view. UIHoverGestureRecognizer has no effect when your app runs in iOS. The following code changes the button’s default color to red as the pointer moves over the button.
class ViewController: UIViewController {
@IBOutlet var button: UIButton!
override func viewDidLoad() { super.viewDidLoad()
let hover = UIHoverGestureRecognizer(target: self, action: #selector(hovering(_:))) button.addGestureRecognizer(hover) }
@objc func hovering(_ recognizer: UIHoverGestureRecognizer) { switch recognizer.state { case .began, .changed: button.titleLabel?.textColor = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) case .ended: button.titleLabel?.textColor = UIColor.link default: break } } }
Topics
Supporting Apple Pencil hover
var altitudeAngle: CGFloat
A value that represents the altitude angle of the hovering pointing device.
A value that represents the azimuth angle of the hovering pointing device in the specified view.
A value that represents the azimuth unit vector of the hovering pointing device in the specified view.
var rollAngle: CGFloat
A value that represents the current barrel-roll angle of Apple Pencil.
var zOffset: CGFloat
A value that represents the normalized distance between the screen and a hovering pointing device, such as Apple Pencil.
Relationships
Inherits From
UIGestureRecognizer
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendableSendableMetatype
See Also
User interactions
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
Adding menus and shortcuts to the menu bar and user interface
Provide quick access to useful actions by adding menus and keyboard shortcuts to your Mac app built with Mac Catalyst.
Handling key presses made on a physical keyboard
Detect when someone presses and releases keys on a physical keyboard.
https://developer.apple.com/documentation/uikit/displaying-a-preferences-window
- UIKit
- Mac Catalyst
- Displaying a Preferences window
Article
Displaying a Preferences window
Provide a Preferences window in your Mac app built with Mac Catalyst so users can manage app preferences defined in a Settings bundle.
Overview
Mac apps typically display app-specific preferences using a Preferences window accessible through the standard Preferences menu item under the app menu in the menu bar.
Mac apps built with Mac Catalyst that include a Settings.bundle file automatically get the Preferences menu item and a Preferences window. When a user selects the Preferences menu item, the system displays a Mac-friendly Preferences window based on the options provided in your Settings bundle. To learn about Settings bundles, see Implementing an iOS Settings Bundle.
Add a Preferences window to your app
To include a Preferences window in your Mac app, add a Settings.bundle file to your Xcode project by pressing Command-N and selecting the Settings Bundle template from the Resources section under iOS. Then click Next to save the file to your project.
Add toolbar tabs to the Preferences window
A Settings bundle can include one or more child panes that allow you to organize your preferences hierarchically (see Hierarchical Preferences). In iOS, the Settings app displays a child pane as a preference row. When the user taps the row, the app displays a new view showing the preferences defined in the child pane’s property list file.
In macOS, the Preferences window displays a child pane as a tab on the window’s toolbar. When the user clicks the tab, they see the preferences provided in the child pane’s property list file.
The tab for a child pane displays the pane’s title and a system-provided icon. To customize the icon, add the following key to the child pane’s property list file:
Icon
Optional. A string with the name of the image file to display as the toolbar tab icon in the Preferences window.
You must include the image file in the Settings bundle that contains the child pane’s property list file.
Confirm changes made with a toggle switch
Another element of the Settings bundle is the Toggle Switch Element, which displays an ON/OFF switch that the user can toggle. Your Mac app can prompt the user for a confirmation when they toggle the switch by including the following keys in the toggle switch element:
TrueConfirmationPrompt
Optional. A dictionary that defines the prompt to present to users when they attempt to turn on the switch.
FalseConfirmationPrompt
Optional. A dictionary that defines the prompt to present to users when they attempt to turn off the switch.
Each dictionary contains the following keys that define the contents of the prompt:
Type
Required. Must be set to PSConfirmationPrompt.
Title
Required. A string with the title of the prompt. The title might not appear on some devices.
Prompt
Required. A string with the body text that the prompt displays.
ConfirmText
Optional. A string with the text displayed in the prompt’s confirmation button. The toggle switch value changes when the user clicks this button.
DenyText
Optional. A string with the text displayed in the prompt’s cancel button. The toggle switch value doesn’t change when the user clicks this button.
Display subtitles for toggle switches
Some iOS apps show descriptive text in a subtitle below a toggle switch using a group item with footer text. While the Preferences window supports this approach, the appearance on a Mac isn’t ideal. Instead, include the following key in the toggle switch element to show a subtitle:
Description
Optional. A longer descriptive string to display under a toggle switch.
See Also
User preferences
Detecting changes in the preferences window
Listen for and respond to a user’s preference changes in your Mac app built with Mac Catalyst using Combine.
https://developer.apple.com/documentation/uikit/detecting-changes-in-the-preferences-window
- UIKit
- Mac Catalyst
- Detecting changes in the preferences window
Sample Code
Detecting changes in the preferences window
Listen for and respond to a user’s preference changes in your Mac app built with Mac Catalyst using Combine.
Download
Xcode 11.1+
Overview
With Combine, your app can listen for changes a user makes to the app’s Preferences window, and respond to those changes. The sample app provides a Preferences window with one setting: background color. When the user selects a color, the background of the main view changes to match their selection.
This sample code project shows how to:
-
Add a Preferences window in a Mac app built with Mac Catalyst.
-
Register default values for the preferences.
-
Retrieve current preference values.
-
Listen for and respond to changes the user makes in the Preferences window.
To use the sample app, open the sample code project in Xcode and select My Mac as the destination. Then, build and run the sample project.
Provide a preferences window in the app
The sample app includes a Settings.bundle file that the system uses to automatically add the standard Preferences menu item to the app menu. Selecting the menu item displays a Preferences window that the system generates based on the preference specifiers defined in the Settings bundle. To learn more, see Displaying a Preferences window.
The Settings bundle for the sample app has a preference specifier for setting the background color of the main view. It also has a child pane preference specifier, which displays a second tab of preferences in the Preferences windows. The Settings bundle file Root.plist defines these specifiers, while the file OtherSettings.plist defines the preference specifiers for the child pane.
Register default preference values
When the user changes preferences in the Preferences window, the window saves them to the application domain of the user defaults system. To store and retrieve the preference values within the app, the sample app uses UserDefaults. However, when you launch the sample app for the first time, the preference values don’t exist in the user defaults system. If the app tries retrieving a value, UserDefaults returns nil.
To ensure that the app always retrieves a non- nil value, the sample app registers the default preference values with the registration domain. However, this domain doesn’t persist these values between app launches, so the sample app registers the default values each time the user launches the app.
// To ensure that the app has a good set of preference values, register // the default values each time the app launches. registerDefaultPreferenceValues()
return true }
The method registerDefaultPreferenceValues() retrieves the default values from the Settings bundle by retrieving the preference specifiers from the Root.plist file and parsing the specifiers for their default value. After retrieving the values, the method registers the default values.
func registerDefaultPreferenceValues() { let preferenceSpecifiers = retrieveSettingsBundlePreferenceSpecifiers(from: "Root.plist") let defaultValuesToRegister = parse(preferenceSpecifiers)
// Register the default values with the registration domain. UserDefaults.standard.register(defaults: defaultValuesToRegister) }
To parse the preference specifiers, the parse() method loops through the array of specifiers, copying the default values into the dictionary defaultValuesToRegister. If the method detects the PSChildPaneSpecifier type, it gets the name of the child pane property list file, and merges the default values in the file into the defaultValuesToRegister dictionary. After gathering the default values, the method returns the dictionary to the caller.
var defaultValuesToRegister = String: Any
// Parse the preference specifiers, copying the default values
// into the defaultValuesToRegister dictionary.
for preferenceItem in preferenceSpecifiers {
if let key = preferenceItem["Key"] as? String,
let defaultValue = preferenceItem["DefaultValue"] {
defaultValuesToRegister[key] = defaultValue
}
// Add child pane preference specifiers. if let type = preferenceItem["Type"] as? String, type == "PSChildPaneSpecifier" { if var file = preferenceItem["File"] as? String { if file.hasSuffix(".plist") == false { file += ".plist" } let morePreferenceSpecifiers = retrieveSettingsBundlePreferenceSpecifiers(from: file) let moreDefaultValuesToRegister = parse(morePreferenceSpecifiers) defaultValuesToRegister.merge(moreDefaultValuesToRegister) { (current, _) in current } } } }
return defaultValuesToRegister }
Retrieve preference values
After registering the default values with the registration domain, the app can retrieve a preference value without the possibility of encountering an unavailable value. To simplify access to the background color preference value, the sample app extends UserDefaults to include properties for each preference value.
extension UserDefaults {
@objc dynamic var backgroundColorValue: Int { return integer(forKey: "backgroundColorValue") }
@objc dynamic var someRandomOption: Bool { return bool(forKey: "someRandomOption") }
}
Handle changes made in the preferences window
As the user changes the background color setting in the Preferences window, the app changes the background color of its main view. To accomplish this, the view controller for the main view creates a subscriber in the viewDidLoad() method. When the background color value changes, the subscriber receives the new value, maps it to a UIColor object, and assigns the color to the view’s backgroundColor property.
var subscriber: AnyCancellable? // Subscriber of preference changes.
override func viewDidLoad() { super.viewDidLoad()
// Set the view's initial background color to the color specified in Preferences. if let colorSetting = BackgroundColors(rawValue: UserDefaults.standard.backgroundColorValue) { view.backgroundColor = colorSetting.currentColor() }
// Listen for changes to the background color preference made in the Preferences window. subscriber = UserDefaults.standard .publisher(for: .backgroundColorValue, options: [.initial, .new]) .map( { BackgroundColors(rawValue: $0)?.currentColor() }) .assign(to: \UIView.backgroundColor, on: self.view) }
See Also
User preferences
Displaying a Preferences window
Provide a Preferences window in your Mac app built with Mac Catalyst so users can manage app preferences defined in a Settings bundle.
https://developer.apple.com/documentation/uikit/showing-help-tags-for-views-and-controls-using-tooltip-interactions
- UIKit
- Mac Catalyst
- Showing help tags for views and controls using tooltip interactions
Sample Code
Showing help tags for views and controls using tooltip interactions
Explain the purpose of interface elements by showing a tooltip when a person positions the pointer over the element.
Download
Xcode 13.0+
Overview
This sample shows how to display a tooltip (also known as a help tag) that explains the purpose of, or provide additional information about, an interface element such as a view or control without shifting a person’s focus away from the primary interface. A tooltip appears when a person positions the pointer over a view or control for a few seconds. The tooltip remains visible for a few seconds or until the pointer moves away from the interface element.
For guidelines on designing the content of your tooltips, see the Help section of the macOS Human Interface Guidelines.
Configure the sample code project
Tooltips are available in the sample app when running in macOS 12 or later. To build and run the sample app:
Add a tooltip to a view
To show a tooltip when the pointer hovers over a view, the sample creates a UIToolTipInteraction object and passes in the default tooltip text. Then the sample adds the interaction to a UIView using the view’s addInteraction(_:) method.
lazy var viewWithDefaultTooltip: UIView = { let view = UIView() view.backgroundColor = UIColor.systemGreen view.addText("Hover the pointer over this view to see its default tooltip.")
let tooltipInteraction = UIToolTipInteraction(defaultToolTip: "The default tooltip for the view.") view.addInteraction(tooltipInteraction)
return view }()
The sample uses the same approach for other types of views too, for instance, to add a tooltip to an instance of UILabel:
lazy var labelWithTooltip: UILabel = { let label = UILabel() label.text = "Hover the pointer over this label to see its tooltip." label.numberOfLines = 0
let tooltipInteraction = UIToolTipInteraction(defaultToolTip: "The label's tooltip.") label.addInteraction(tooltipInteraction)
return label }()
Add a tooltip to a control
For interface elements that derive from UIControl, such as UIButton, the sample uses the toolTip property to set the default text that appears in the tooltip instead of adding an interaction to the control.
lazy var buttonWithTooltip: UIButton = { var configuration = UIButton.Configuration.filled() configuration.title = "Buy" configuration.subtitle = "Only $9.99" configuration.titleAlignment = .center
let action = UIAction { _ in print("Thank you for your purchase.") }
let button = UIButton(configuration: configuration, primaryAction: action) button.toolTip = "Click to buy this item. You'll have a chance to change your mind before confirming your purchase." button.preferredBehavioralStyle = .pad
return button }()
Change the tooltip text of a view
Setting the defaultToolTip property of a tooltip interaction and setting the toolTip property of a control are convenient ways to show tooltip text that don’t change while the app runs. However, there may be times when an app needs to determine the contents of the tooltip based on the state of the app or logic specific to the app. For instance, the sample app looks up the name of a view’s background color and displays the name in a tooltip when the pointer hovers over that view.
To show the background color name in a tooltip, the sample creates an instance of UIToolTipInteraction and sets its delegate property to an instance of ViewWithBackgroundColorTooltip, which is a custom view that conforms to the UIToolTipInteractionDelegate protocol. Then the sample adds the interaction to the view.
lazy var viewWithBackgroundColorTooltip: UIView = { let view = ViewWithBackgroundColorTooltip() view.backgroundColor = UIColor.systemYellow view.addText("Hover the pointer over this view to see the name of the view's background color.")
let tooltipInteraction = UIToolTipInteraction() tooltipInteraction.delegate = view view.addInteraction(tooltipInteraction)
Next, ViewWithBackgroundColorTooltip implements the toolTipInteraction(_:configurationAt:) method, and returns a UIToolTipConfiguration object that contains the name of the background color as the text of the tooltip. If the color name isn’t available, the method returns nil, which prevents the tooltip from displaying.
class ViewWithBackgroundColorTooltip: UIView, UIToolTipInteractionDelegate {
let configuration: UIToolTipConfiguration? if let accessibilityName = backgroundColor?.accessibilityName { configuration = UIToolTipConfiguration(toolTip: "The color is (accessibilityName).") } else { configuration = nil }
return configuration }
}
Change the tooltip text of a control
To change the tooltip text of a control like the sample’s shopping cart button, the sample provides a tooltip interaction delegate as it did with the custom view. But instead of creating a tooltip interaction, it sets the button’s toolTip property to the default text. This causes the control to create a UIToolTipInteraction object and assign it to the toolTipInteraction property. The sample then uses the property to assign a delegate to the interaction.
lazy var shoppingCartButtonWithTooltip: UIButton = { var configuration = UIButton.Configuration.filled() configuration.title = "Add to Cart" configuration.image = UIImage(systemName: "cart.circle") configuration.imagePlacement = NSDirectionalRectEdge.leading configuration.imagePadding = 4
let action = UIAction { [unowned self] _ in self.cartItemCount += 1 }
let button = UIButton(configuration: configuration, primaryAction: action) button.toolTip = "Click to add the item to your cart. Your cart is empty." button.toolTipInteraction?.delegate = self
The sample also implements the toolTipInteraction(_:configurationAt:) delegate method, which returns a UIToolTipConfiguration object that contains the tooltip text describing the purpose of the button and the number of items in the shopping cart.
let text: String switch cartItemCount { case 0: text = "Click to add the item to your cart. Your cart is empty." case 1: text = "Click to add the item to your cart. Your cart contains (cartItemCount) item." default: text = "Click to add the item to your cart. Your cart contains (cartItemCount) items." }
return UIToolTipConfiguration(toolTip: text) }
Specify the hover region
In addition to setting the tooltip text in a UIToolTipConfiguration object, a delegate can specify the region of an interface element where the pointer must hover to trigger the display of the tooltip. The sample app, for example, shows a view that displays a tooltip after positioning the pointer over the top or bottom regions of the view, but not when the pointer is over the middle area.
To determine whether the pointer location is in the top or bottom region of the view, the sample uses the point value that the method toolTipInteraction(_:configurationAt:) provides. When the pointer is in one of those regions, the delegate method returns a tooltip configuration that contains the tooltip text and the source rectangle, which defines the area of the view that the pointer must hover over to trigger the display of the tooltip.
class ViewWithTooltipRegion: UIView, UIToolTipInteractionDelegate {
var topRect = self.bounds var bottomRect = self.bounds
let partHeight = self.bounds.size.height / 3 topRect.size.height = partHeight bottomRect.size.height = partHeight bottomRect.origin.y = partHeight * 2
// Display the tooltip if the pointer within the top or bottom rects. if topRect.contains(point) { return UIToolTipConfiguration(toolTip: "Top area of the view.", in: topRect) } else if bottomRect.contains(point) { return UIToolTipConfiguration(toolTip: "Bottom area of the view.", in: bottomRect) }
// Pointer is in the middle of the view; don't display a tooltip. return nil }
In another example, the sample uses the source rectangle of a tooltip configuration to specify the region of selected text in a text view. When hovering the pointer over the selected text, a tooltip appears but it doesn’t appear when the pointer hovers over unselected text.
class TextViewWithTooltip: UITextView, UIToolTipInteractionDelegate {
guard let selectedTextRange = self.selectedTextRange, selectedTextRange.isEmpty == false else { return nil }
var unionedRect = firstRect(for: selectedTextRange) for selectionRect in selectionRects(for: selectedTextRange) { unionedRect = unionedRect.union(selectionRect.rect) }
if let selectedText = text(in: selectedTextRange) { return UIToolTipConfiguration(toolTip: "Selected text: (selectedText)", in: unionedRect) }
return nil }
See Also
Tooltips
class UIToolTipInteraction
An interaction object that makes it possible to show a tooltip when hovering a pointer over a view or control.
protocol UIToolTipInteractionDelegate
An interface that provides tooltip settings to an interaction.
https://developer.apple.com/documentation/uikit/uitooltipinteraction
- UIKit
- UIToolTipInteraction
Class
UIToolTipInteraction
An interaction object that makes it possible to show a tooltip when hovering a pointer over a view or control.
@MainActor class UIToolTipInteraction
Overview
To show a tooltip when the pointer hovers over a view, add a UIToolTipInteraction object to the view. For example, the following code listings shows how to add a tooltip to a label:
let label = UILabel() label.text = "Label with a tooltip"
let tooltipInteraction = UIToolTipInteraction(defaultToolTip: "The label's tooltip.") label.addInteraction(tooltipInteraction)
If you want your app to determine the tooltip text at a later time — for instance, to reflect the current state of your app — set the interaction’s delegate property to an object that conforms to the UIToolTipInteractionDelegate protocol.
To add a tooltip to a control derived from UIControl, use the convenience property toolTip; for example, to add a tooltip to the button:
let button = UIButton(configuration: configuration, primaryAction: action) button.toolTip = "Click to buy this item. You'll have a chance to change your mind before confirming your purchase."
Setting the toolTip property creates a tooltip interaction for the control, which you can retrieve from the toolTipInteraction property.
Topics
Creating a tooltip interaction
init()
Creates a tooltip interaction object.
init(defaultToolTip: String)
Creates a tooltip interaction object and sets the default tooltip text.
Managing the interaction
var isEnabled: Bool
A Boolean value that indicates whether the tooltip interaction is in the enabled state.
var defaultToolTip: String?
The text that appears in a tooltip by default.
Providing tooltip configurations
var delegate: (any UIToolTipInteractionDelegate)?
An object that provides text that a tooltip displays instead of the default text.
protocol UIToolTipInteractionDelegate
An interface that provides tooltip settings to an interaction.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendableUIInteraction
See Also
Tooltips
Showing help tags for views and controls using tooltip interactions
Explain the purpose of interface elements by showing a tooltip when a person positions the pointer over the element.
https://developer.apple.com/documentation/uikit/uitooltipinteractiondelegate
- UIKit
- UIToolTipInteractionDelegate
Protocol
UIToolTipInteractionDelegate
An interface that provides tooltip settings to an interaction.
@MainActor protocol UIToolTipInteractionDelegate : NSObjectProtocol
Overview
A tooltip interaction delegate provides configuration information about a tooltip. You can, for instance, use the delegate to change the text of a tooltip.
To change the tooltip text, set a tooltip interaction’s delegate property to an object that conforms to the UIToolTipInteractionDelegate protocol and implements the toolTipInteraction(_:configurationAt:) method. For example, in the following code listing, the code creates a new view and assigns its background color. Then the code creates a UIToolTipInteraction object, sets the delegate equal to the view, and adds the interaction to the view.
lazy var viewWithBackgroundColorTooltip: UIView = { let view = ViewWithBackgroundColorTooltip() view.backgroundColor = UIColor.systemYellow
let tooltipInteraction = UIToolTipInteraction() tooltipInteraction.delegate = view view.addInteraction(tooltipInteraction)
return view }()
The delegate’s implementation of the toolTipInteraction(_:configurationAt:) method looks up the accessibilityName of the view’s background color. If the name is available, the method creates a UIToolTipConfiguration object, passing in the name of the color. Then the method returns the configuration. If the name isn’t available, the method returns nil, which prevents the display of the tooltip.
class ViewWithBackgroundColorTooltip: UIView, UIToolTipInteractionDelegate {
let configuration: UIToolTipConfiguration? if let accessibilityName = backgroundColor?.accessibilityName { configuration = UIToolTipConfiguration(toolTip: "The color is (accessibilityName).") } else { configuration = nil }
return configuration }
}
In addition to changing the tooltip text, you can also specify the region within a view or control where a person must position the pointer to trigger the display of the tooltip. To specify the region, create the tooltip configuration using the init(toolTip:in:) method.
Topics
Providing a tooltip configuration
Asks the delegate for a tooltip configuration that describes the tooltip settings.
class UIToolTipConfiguration
An object that a tooltip interaction delegate uses to describe the tooltip settings.
Relationships
Inherits From
NSObjectProtocol
See Also
Tooltips
Showing help tags for views and controls using tooltip interactions
Explain the purpose of interface elements by showing a tooltip when a person positions the pointer over the element.
class UIToolTipInteraction
An interaction object that makes it possible to show a tooltip when hovering a pointer over a view or control.
https://developer.apple.com/documentation/uikit/creating-a-mac-version-of-your-ipad-app)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/choosing-a-user-interface-idiom-for-your-mac-app)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/optimizing-your-ipad-app-for-mac)
https://developer.apple.com/documentation/uikit/uikit-catalog-creating-and-customizing-views-and-controls)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/building-and-improving-your-app-with-mac-catalyst)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/displaying-a-checkbox-in-your-mac-app-built-with-mac-catalyst)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/removing-the-title-bar-in-your-mac-app-built-with-mac-catalyst)
https://developer.apple.com/documentation/uikit/toolbar)
https://developer.apple.com/documentation/uikit/navigating-an-app-s-user-interface-using-a-keyboard)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/adding-menus-and-shortcuts-to-the-menu-bar-and-user-interface)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/handling-key-presses-made-on-a-physical-keyboard)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uihovergesturerecognizer)
https://developer.apple.com/documentation/uikit/displaying-a-preferences-window)
https://developer.apple.com/documentation/uikit/detecting-changes-in-the-preferences-window)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/showing-help-tags-for-views-and-controls-using-tooltip-interactions)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uitooltipinteraction)
https://developer.apple.com/documentation/uikit/uitooltipinteractiondelegate)
https://developer.apple.com/documentation/uikit/uidocumentpickerextensionviewcontroller
- UIKit
- UIDocumentPickerExtensionViewController Deprecated
Class
UIDocumentPickerExtensionViewController
The principal class for the Document Picker View Controller extension.
iOS 8.0–14.0DeprecatediPadOS 8.0–14.0DeprecatedMac Catalyst 13.1–14.0DeprecatedvisionOS 1.0–1.0Deprecated
@MainActor class UIDocumentPickerExtensionViewController
Overview
The Document Picker View Controller extension can perform import and export operations on its own. If you want to support open and move operations, you must pair it with a File Provider extension.
When creating a Document Picker extension, you must subclass UIDocumentPickerExtensionViewController to provide the document picker’s user interface. Your subclass presents a list of available documents and destinations to the user. When the user makes a selection, you trigger the file transfer and pass the selected URL .
Topics
Managing the user interface
func dismissGrantingAccess(to: URL?)
Dismisses the document picker.
var documentPickerMode: UIDocumentPickerMode
The document picker’s file-transfer operation. (read-only)
var documentStorageURL: URL?
The root URL for documents provided by the corresponding File Provider extension. (read-only)
var originalURL: URL?
The URL of the file to be exported. (read-only)
func prepareForPresentation(in: UIDocumentPickerMode)
Performs any custom configuration of the document picker view controller.
var providerIdentifier: String
An identifier shared by this Document Picker extension and its corresponding File Provider extension. (read-only)
An array of valid uniform type identifiers.
Relationships
Inherits From
UIViewController
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSExtensionRequestHandlingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIActivityItemsConfigurationProvidingUIAppearanceContainerUIContentContainerUIFocusEnvironmentUIPasteConfigurationSupportingUIResponderStandardEditActionsUIStateRestoringUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Document provider
class NSFileProviderExtension
The principal class for the nonreplicated File Provider extension.
https://developer.apple.com/documentation/uikit/uitextdocumentproxy
- UIKit
- UITextDocumentProxy
Protocol
UITextDocumentProxy
An object that provides textual context to a custom keyboard.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor protocol UITextDocumentProxy : UIKeyInput
Mentioned in
Handling text interactions in custom keyboards
Overview
Through conformance to the UIKeyInput protocol, a text document proxy enables a custom keyboard (which is based on the UIInputViewController class) to insert and delete text, to adjust the position of the insertion point, and to determine whether a text input object is empty. The text document proxy uses the keyboard’s textDocumentProxy property to do this.
For more about using a text document proxy, see UIInputViewController and Creating a custom keyboard.
Topics
Getting the text-input mode
var documentInputMode: UITextInputMode?
The text-input mode for the keyboard.
Required
Obtaining textual context around the insertion point
var documentContextAfterInput: String?
Textual context after the insertion point in the current text input object.
var documentContextBeforeInput: String?
Textual context before the insertion point in the current text input object.
Adjusting the insertion point position
func adjustTextPosition(byCharacterOffset: Int)
Moves the insertion point forward or backward in the current text input object.
Getting the selected text
var selectedText: String?
The currently selected text in the document.
Managing marked text
func setMarkedText(String, selectedRange: NSRange)
Inserts the provided text and marks it to indicate that it’s part of an active input session.
func unmarkText()
Unmarks the currently marked text.
Distinguishing changes in the document
var documentIdentifier: UUID
The unique identifier for the document.
Relationships
Inherits From
NSObjectProtocolUIKeyInputUITextInputTraits
See Also
Custom keyboard
protocol UIInputViewAudioFeedback
A property that enables a custom input or keyboard accessory view to play standard keyboard input clicks.
class UIInputViewController
The primary view controller for a custom keyboard app extension.
class UILexicon
A read-only array of term pairs, each in a lexicon entry object, for a custom keyboard.
class UILexiconEntry
A read-only term pair, available within a lexicon object, for a custom keyboard.
https://developer.apple.com/documentation/uikit/uiinputviewaudiofeedback
- UIKit
- UIInputViewAudioFeedback
Protocol
UIInputViewAudioFeedback
A property that enables a custom input or keyboard accessory view to play standard keyboard input clicks.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor protocol UIInputViewAudioFeedback : NSObjectProtocol
Overview
Implement this protocol in your custom subclass of UIView that you associate with your custom input nib file. For more information, see Text Programming Guide for iOS.
Implementation of this protocol is optional but expected.
Topics
Enabling input clicks
var enableInputClicksWhenVisible: Bool
Specifies whether or not an input view enables input clicks.
Relationships
Inherits From
NSObjectProtocol
See Also
Custom keyboard
protocol UITextDocumentProxy
An object that provides textual context to a custom keyboard.
class UIInputViewController
The primary view controller for a custom keyboard app extension.
class UILexicon
A read-only array of term pairs, each in a lexicon entry object, for a custom keyboard.
class UILexiconEntry
A read-only term pair, available within a lexicon object, for a custom keyboard.
https://developer.apple.com/documentation/uikit/uiinputviewcontroller
https://developer.apple.com/documentation/uikit/uilexicon
- UIKit
- UILexicon
Class
UILexicon
A read-only array of term pairs, each in a lexicon entry object, for a custom keyboard.
@MainActor class UILexicon
Mentioned in
Configuring a custom keyboard interface
Overview
To obtain the lexicon, call the requestSupplementaryLexicon(completion:) method of the UIInputViewController class. This method can be called only from a custom keyboard app extension. A lexicon contains words from various sources, including:
-
Unpaired first names and last names from the user’s Address Book database
-
A common words dictionary
Apple intends for you to consider the words in a lexicon object as supplementary to an autocorrection/suggestion lexicon of your own design. For information on custom keyboards, see Custom Keyboard in App Extension Programming Guide.
Topics
Accessing the lexicon
A read-only array of term pairs for use by a custom keyboard.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCopyingNSObjectProtocolSendable
See Also
Custom keyboard
protocol UITextDocumentProxy
An object that provides textual context to a custom keyboard.
protocol UIInputViewAudioFeedback
A property that enables a custom input or keyboard accessory view to play standard keyboard input clicks.
class UIInputViewController
The primary view controller for a custom keyboard app extension.
class UILexiconEntry
A read-only term pair, available within a lexicon object, for a custom keyboard.
https://developer.apple.com/documentation/uikit/uilexiconentry
- UIKit
- UILexiconEntry
Class
UILexiconEntry
A read-only term pair, available within a lexicon object, for a custom keyboard.
@MainActor class UILexiconEntry
Overview
You can employ a lexicon entry by matching user input against the entry’s userInput value, and then inserting into the current text input object the corresponding documentText value. For example, if the user typed the string “iphone”, the lexicon entry with that exact, case-sensitive string in the userInput property has the string “iPhone” in the corresponding documentText property.
In some cases, the documentText string is in a different text script than the userInput string.
For information on custom keyboards, which are based on the UIInputViewController class, see Creating a custom keyboard.
Topics
Accessing a lexicon entry
var documentText: String
Text to be inserted into a text input object by a custom keyboard, corresponding to the user input value in the same lexicon entry.
var userInput: String
Text to match, during user input, to provide appropriate output to a text document from the document text value in the same lexicon entry.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCopyingNSObjectProtocolSendable
See Also
Custom keyboard
protocol UITextDocumentProxy
An object that provides textual context to a custom keyboard.
protocol UIInputViewAudioFeedback
A property that enables a custom input or keyboard accessory view to play standard keyboard input clicks.
class UIInputViewController
The primary view controller for a custom keyboard app extension.
class UILexicon
A read-only array of term pairs, each in a lexicon entry object, for a custom keyboard.
https://developer.apple.com/documentation/uikit/uidocumentpickerextensionviewcontroller)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uitextdocumentproxy)
https://developer.apple.com/documentation/uikit/uiinputviewaudiofeedback)
https://developer.apple.com/documentation/uikit/uiinputviewcontroller)
https://developer.apple.com/documentation/uikit/uilexicon)
https://developer.apple.com/documentation/uikit/uilexiconentry)
https://developer.apple.com/documentation/uikit/customizing-the-behavior-of-segue-based-presentations
- UIKit
- Resource management
- Customizing the behavior of segue-based presentations
Article
Customizing the behavior of segue-based presentations
Pass data between view controllers during a segue, and programmatically control when segues occur.
Overview
When the user triggers a segue, UIKit presents the view controller using the options found in your storyboard. UIKit also provides opportunities for you to modify the segue process dynamically, either by preventing the segue from occurring or by doing extra work when a segue occurs.
For information on how to create a segue, see Specify presentations visually in your storyboard file.
Configure the presentation style of the transition
The segue’s type determines what kind of animations UIKit uses when presenting and dismissing the segue, as the table below shows. You specify the type when you create the segue, but you can also change it in the attributes inspector later.
| Segue type | Behavior |
|---|---|
| Show (Push) | Displays the view controller modally unless a parent view controller implements the show(_:sender:) action method, in which case that view controller defines the presentation behavior. For example, a UINavigationController pushes the new view controller onto its navigation stack. |
| Show Detail (Replace) | Displays the view controller modally unless a parent view controller implements the showDetailViewController(_:sender:) action method, in which case that view controller defines the presentation behavior. For example, a UISplitViewController replaces its second child view controller (the detail controller) with the new view controller. |
| Present Modally | Displays the view controller modally using the specified presentation and transition styles. |
| Present as Popover | In a horizontally regular environment, UIKit presents the view controller in a popover. In a horizontally compact environment, UIKit presents the view controller modally. |
For more information about how UIKit performs segues involving the Show and Show Detail presentation styles, see Let the current context define the presentation technique.
Prevent a segue based on dynamic conditions
When you don’t want the user to leave the current view controller, tell UIKit not to perform a segue by returning false from the shouldPerformSegue(withIdentifier:sender:) method of the source view controller. Use that method to perform any checks you need to determine whether the segue can proceed. For example, return false if the view controller’s content is invalid and requires corrective user actions. Returning true lets the segue continue, but returning false causes the segue to fail silently.
Pass data to the presented view controller
Because UIKit creates and presents the view controller automatically during a segue, use the prepare(for:sender:) method to pass any data to that view controller before the segue occurs. Implement the method on the view controller containing the object that initiated the segue. Fetch the new view controller from the provided UIStoryboardSegue object, along with information about which segue was triggered.
In the following code example, the current view controller fetches the image associated with the selected table row and passes that image to the new view controller.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller. if let imageVC = segue.destination as? ImageViewController {
// Fetch the image for the selected row. let image = getImageForSelectedRow() imageVC.currentImage = image } }
Use the delegate design pattern to pass data from a presented view controller ) method.
Understand the sequence of events during a segue
Although UIKit handles segues automatically, there are many places where you can perform work related to displaying the new view controller. The following figure shows the flow of events that happens from the time the user triggers a segue until the process is complete. The main place to perform perform segue-related actions is the current view controller’s prepare(for:sender:) method, but you also may perform tasks during the creation of the new view controller.
See Also
Storyboards
Dismissing a view controller with an unwind segue
Configure an unwind segue in your storyboard file that dynamically chooses the most appropriate view controller to display next.
class UIStoryboard
An encapsulation of the design-time view controller graph represented in an Interface Builder storyboard resource file.
class UIStoryboardSegue
An object that prepares for and performs the visual transition between two view controllers.
class UIStoryboardUnwindSegueSource
An encapsulation of information about an unwind segue.
https://developer.apple.com/documentation/uikit/dismissing-a-view-controller-with-an-unwind-segue
https://developer.apple.com/documentation/uikit/uistoryboard
- UIKit
- UIStoryboard
Class
UIStoryboard
An encapsulation of the design-time view controller graph represented in an Interface Builder storyboard resource file.
tvOSvisionOS 1.0–1.0Deprecated
@MainActor class UIStoryboard
Mentioned in
Displaying and managing views with a view controller
Overview
A UIStoryboard object manages archived versions of your app’s view controllers. At design time, you configure the content of your view controllers visually, and Xcode saves the data needed to recreate that interface in a storyboard file in your app’s bundle. When you want to create a new view controller programmatically, first create a UIStoryboard object and specify the appropriate name and bundle information. Then use that object to instantiate the specific view controller that you want.
During the instantiation process, UIStoryboard creates your view controller programmatically using its doc://com.apple.documentation/documentation/oslog/oslogentry/init(coder:) method. The storyboard passes the view controller’s data archive to that method, which then uses the data to recreate the state of the view controller and its views. If you have a custom initialization method for your view controller, you can ask the storyboard to instantiate your view controller using a block you provide. You can use this block to call your custom initialization method, passing any extra data your view controller needs.
For visionOS apps, you can load existing storyboards, but you can’t add content specific to the platform. Migrate your interface code to SwiftUI as soon as possible.
Topics
Getting a Storyboard Object
init(name: String, bundle: Bundle?)
Creates and returns a storyboard object for the specified resource file.
Loading the Initial View Controller
Creates the initial view controller and initializes it with the data from the storyboard.
Creates the initial view controller from the storyboard and initializes it using your custom initialization code.
Instantiating Storyboard View Controllers
Creates the view controller with the specified identifier and initializes it with the data from the storyboard.
Creates the specified view controller from the storyboard and initializes it using your custom initialization code.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendable
See Also
Storyboards
Customizing the behavior of segue-based presentations
Pass data between view controllers during a segue, and programmatically control when segues occur.
Dismissing a view controller with an unwind segue
Configure an unwind segue in your storyboard file that dynamically chooses the most appropriate view controller to display next.
class UIStoryboardSegue
An object that prepares for and performs the visual transition between two view controllers.
class UIStoryboardUnwindSegueSource
An encapsulation of information about an unwind segue.
https://developer.apple.com/documentation/uikit/uistoryboardsegue
https://developer.apple.com/documentation/uikit/uistoryboardunwindseguesource
- UIKit
- UIStoryboardUnwindSegueSource
Class
UIStoryboardUnwindSegueSource
An encapsulation of information about an unwind segue.
@MainActor class UIStoryboardUnwindSegueSource
Overview
You don’t create instances of this class yourself. UIKit creates an unwind segue source object in response to the triggering of an unwind segue. It passes the source object to other view controller methods that determine the destination of the unwind segue. The information in an unwind segue source object includes the view controller being dismissed by the segue and the action method responsible for the dismissal.
Topics
Getting the unwind segue attributes
var source: UIViewController
The view controller being dismissed by the unwind segue.
var unwindAction: Selector
The action method associated with the unwind segue.
var sender: Any?
The object that performed the unwind action.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendable
See Also
Storyboards
Customizing the behavior of segue-based presentations
Pass data between view controllers during a segue, and programmatically control when segues occur.
Dismissing a view controller with an unwind segue
Configure an unwind segue in your storyboard file that dynamically chooses the most appropriate view controller to display next.
class UIStoryboard
An encapsulation of the design-time view controller graph represented in an Interface Builder storyboard resource file.
class UIStoryboardSegue
An object that prepares for and performs the visual transition between two view controllers.
https://developer.apple.com/documentation/uikit/uiimageasset
- UIKit
- UIImageAsset
Class
UIImageAsset
A container for a collection of images that represent multiple ways of describing a single piece of artwork.
tvOS
class UIImageAsset
Overview
A common use case for UIImageAsset is the grouping of multiple images of the same item at different display scales. Image asset objects aren’t assigned to instances of UIImage rather; UIImage provides an asset when multiple representations of an image are available. Images retrieved from image asset catalogs using the init(named:) or init(named:in:compatibleWith:) methods automatically have an image asset object that allows access to other images from the catalog.
Register an image
When you register an image with an image asset, you associate a UITraitCollection object with the image. The trait collection must contain the displayScale and userInterfaceIdiom trait properties. If you don’t define these traits in the trait collection, the following defaults are assigned:
-
displayScale=1.0 -
userInterfaceIdiom=UIUserInterfaceIdiom.unspecified
For example, if you create a trait collection that only contains a horizontal size class, the default display scale and idiom are added when the image is registered.
Retrieve an image
When you retrieve or unregister an image from an image asset, you do so using the trait collection that was used to register the image. To ensure the correct image is retrieved, the trait collection used must contain the displayScale and userInterfaceIdiom traits. If these traits aren’t defined in the trait collection, the following defaults are assigned:
-
displayScale= scale of the current device -
userInterfaceIdiom= the type of interface used on the current device
For example, if you create a trait collection that only contains a horizontal size class, the default display scale and idiom of the current device are added when searching the UIImageAsset for an image.
UIImageView automatically retrieves the correct image when traitCollectionDidChange(_:) is called on it.
Topics
Initializing an image asset
init()
Creates a new image asset object.
init?(coder: NSCoder)
Creates an image asset from data in an unarchiver.
Registering and unregistering images
func register(UIImage, with: UITraitCollection)
Registers an image with the specified trait collection.
func register(UIImage, with: UIImage.Configuration)
Registers an image with the specified image configuration details.
func unregister(imageWith: UITraitCollection)
Unregisters the image with the specified trait collection from the image asset.
func unregisterImage(with: UIImage.Configuration)
Unregisters the image with the specified image configuration details from the image asset.
Retrieving an image from an image asset
Retrieves the variant of the image that best matches the specified trait collection.
Retrieves the variant of the image that best matches the specified image configuration details.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSSecureCodingSendableSendableMetatype
See Also
Assets
class NSDataAsset
An object from a data set type stored in an asset catalog.
https://developer.apple.com/documentation/uikit/nsdataasset
- UIKit
- NSDataAsset
Class
NSDataAsset
An object from a data set type stored in an asset catalog.
class NSDataAsset
Overview
The object’s content is stored as a set of one or more files with associated device attributes. These sets can also be tagged for use as on-demand resources.
Initialize data assets
Data assets are initialized from a named data set in an asset catalog. You create data sets during app development. Each data set contains one or more data files. Each file has associated attributes for features of the device, including the minimum amount of memory and the version of Metal. When you initialize the data asset, the system selects the data file that best matches the current device.
For more information on the data set type in an asset catalog, see Data Set Type in Asset Catalog Format Reference. For information on asset catalogs, see Managing assets with asset catalogs.
Access the data
You access the data file by using the data property. Because the property is of type NSData it provides methods for accessing the raw data only as bytes and ranges of bytes.
To access structured data, convert the bytes into the appropriate format. The system can convert some data types for you. One example is XML data using the init(data:) method of XMLParser. Other data types require code for parsing and converting the raw data. You may need to convert larger data files incrementally.
Topics
Initializing the data asset
convenience init?(name: NSDataAssetName)
Initializes and returns an object with a reference to the named data asset in an asset catalog.
init?(name: NSDataAssetName, bundle: Bundle)
Initializes and returns an object with a reference to the named data asset that’s in an asset catalog in the specified bundle.
Accessing data
var data: Data
The raw data values in the data asset.
Getting data asset information
var name: NSDataAssetName
The name of the data set in the asset catalog.
typealias NSDataAssetName
The name of a data asset.
var typeIdentifier: String
The uniform type identifier for the data asset.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCopyingNSObjectProtocolSendableSendableMetatype
See Also
Assets
class UIImageAsset
A container for a collection of images that represent multiple ways of describing a single piece of artwork.
https://developer.apple.com/documentation/uikit/uinib
- UIKit
- UINib
Class
UINib
An object that contains Interface Builder nib files.
tvOSvisionOS 1.0–1.0Deprecated
@MainActor class UINib
Overview
A UINib object caches the contents of a nib file in memory, ready for unarchiving and instantiation. When your app needs to instantiate the contents of the nib file, it can do so without having to load the data from the nib file first, which improves performance. The UINib object can automatically release this cached nib data to free up memory for your app under low-memory conditions, reloading that data the next time your app instantiates the nib.
Your app should use UINib objects whenever it needs to repeatedly instantiate the same nib data. For example, if your table view uses a nib file to instantiate table view cells, caching the nib in a UINib object can improve performance.
When you create a UINib object using the contents of a nib file, the object loads the object graph in the referenced nib file, but it doesn’t unarchive it yet. To unarchive all of the nib data and instantiate the nib, your app calls the instantiate(withOwner:options:) method. For more information about the steps that the UINib object follows to instantiate the nib’s object graph, see Resource Programming Guide.
Topics
Creating a nib object
init(nibName: String, bundle: Bundle?)
Returns a nib object from the nib file in the specified bundle.
init(data: Data, bundle: Bundle?)
Creates a nib object from nib data stored in memory.
Retrieving objects from the nib file
Unarchives and instantiates the in-memory contents of the nib object’s nib file, creating a distinct object tree and set of top-level objects.
struct OptionsKey
Options that specify how to unarchive and instantiate the nib.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendable
https://developer.apple.com/documentation/uikit/customizing-the-behavior-of-segue-based-presentations)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/dismissing-a-view-controller-with-an-unwind-segue)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uistoryboard)
https://developer.apple.com/documentation/uikit/uistoryboardsegue)
https://developer.apple.com/documentation/uikit/uistoryboardunwindseguesource)
https://developer.apple.com/documentation/uikit/uiimageasset)
https://developer.apple.com/documentation/uikit/nsdataasset)
https://developer.apple.com/documentation/uikit/uinib)
https://developer.apple.com/documentation/uikit/uiuseractivityrestoring
- UIKit
- UIUserActivityRestoring
Protocol
UIUserActivityRestoring
The protocol you adopt to restore an object’s state from a user activity.
tvOS
@MainActor protocol UIUserActivityRestoring : NSObjectProtocol
Topics
Restoring user activity state
func restoreUserActivityState(NSUserActivity)
Restores the state necessary to continue the specified user activity.
Required
Relationships
Inherits From
NSObjectProtocol
Conforming Types
UIAccessibilityElementUIActionSheetUIActivityIndicatorViewUIActivityViewControllerUIAlertControllerUIAlertViewUIApplicationUIBackgroundExtensionViewUIButtonUICalendarViewUICloudSharingControllerUICollectionReusableViewUICollectionViewUICollectionViewCellUICollectionViewControllerUICollectionViewListCellUIColorPickerViewControllerUIColorWellUIContentUnavailableViewUIControlUIDatePickerUIDocumentUIDocumentBrowserViewControllerUIDocumentMenuViewControllerUIDocumentPickerExtensionViewControllerUIDocumentPickerViewControllerUIDocumentViewControllerUIEventAttributionViewUIFontPickerViewControllerUIImagePickerControllerUIImageViewUIInputViewUIInputViewControllerUILabelUIListContentViewUIManagedDocumentUINavigationBarUINavigationControllerUIPageControlUIPageViewControllerUIPasteControlUIPickerViewUIPopoverBackgroundViewUIProgressViewUIReferenceLibraryViewControllerUIRefreshControlUIResponderUISceneUIScrollViewUISearchBarUISearchContainerViewControllerUISearchControllerUISearchTextFieldUISegmentedControlUISliderUISplitViewControllerUIStackViewUIStandardTextCursorViewUIStepperUISwitchUITabBarUITabBarControllerUITableViewUITableViewCellUITableViewControllerUITableViewHeaderFooterViewUITextFieldUITextFormattingViewControllerUITextViewUIToolbarUIVideoEditorControllerUIViewUIViewControllerUIVisualEffectViewUIWebViewUIWindowUIWindowScene
See Also
User activities
class NSUserActivity
A representation of the state of your app at a moment in time.
https://developer.apple.com/documentation/uikit/uiactivity
- UIKit
- UIActivity
Class
UIActivity
An abstract class that you subclass to implement app-specific services.
class UIActivity
Mentioned in
Adding custom actions and activities
Overview
You should subclass UIActivity only if you want to provide custom services to people. A service takes data that’s passed to it, does something to that data, and returns the results. For example, a social media service might take whatever text, images, or other content is provided to it and post them to a person’s account. Activity objects are used in conjunction with a UIActivityViewController object, which is responsible for presenting services to people.
The system already provides support for many standard services and makes them available through the UIActivityViewController object. For example, the standard activity view controller supports emailing data, posting items to one of a person’s social media accounts, and several other options. You don’t have to provide custom services for any of the built-in types.
Subclassing notes
This class must be subclassed before it can be used. The job of an activity object is to act on the data provided to it and to provide some meta information that iOS can display to people. For more complex services, an activity object can also display a custom user interface and use it to gather additional information from people.
Methods to override
When subclassing, you must always override the following methods and use them to provide information about your service:
-
activityType -
activityTitle -
activityImage -
canPerform(withActivityItems:) -
prepare(withActivityItems:) -
activityCategory
If your canPerform(withActivityItems:) method indicates that your subclass is able to operate on the specified data, the active UIActivityViewController object displays your service to people. When a person selects your service, the activity view controller calls the prepare(withActivityItems:) method followed by only one of these methods:
-
activityViewController— Returns a view controller to present to a person. If your service requires additional input from a person, override this method and use it to return the view controller object responsible for presenting your custom UI. (You don’t need to present the view controller yourself.) After your view controller object gathers the needed input, it’s responsible for initiating the task associated with the service. -
perform()— Performs the service without displaying any additional UI. If your service doesn’t need additional input from a person, override this method and perform the task associated with the service.
Topics
Getting the activity information
class var activityCategory: UIActivity.Category
The category of the activity, which may be used to group activities in the UI.
enum Category
An enumeration that defines categories of activities.
var activityType: UIActivity.ActivityType?
The type of service being provided.
struct ActivityType
A structure that describes the types of activities for which the system has built-in support.
var activityTitle: String?
A user-readable string that describes the service.
var activityImage: UIImage?
An image that identifies the service to the user.
Performing the activity
Queries whether the service can act on the specified data items.
func prepare(withActivityItems: [Any])
Prepares your service to act on the specified data.
var activityViewController: UIViewController?
The view controller to present to the user.
func perform()
Performs the service when no custom view controller is provided.
func activityDidFinish(Bool)
Notifies the system that your activity object has completed its work.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocol
See Also
Services
class UIActivityViewController
A view controller that you use to offer standard services from your app.
protocol UIActivityItemSource
A set of methods that an activity view controller uses to retrieve the data items to act on.
class UIActivityItemProvider
A proxy for data that passes to an activity view controller.
https://developer.apple.com/documentation/uikit/uiactivityviewcontroller
- UIKit
- UIActivityViewController
Class
UIActivityViewController
A view controller that you use to offer standard services from your app.
@MainActor class UIActivityViewController
Mentioned in
Collaborating and sharing copies of your data
Overview
The system provides several standard services, such as copying items to the pasteboard, posting content to social media sites, sending items via email or SMS, and more. Apps can also define custom services.
Your app is responsible for configuring, presenting, and dismissing this view controller. Configuration for the view controller involves specifying the data objects on which the view controller should act. (You can also specify the list of custom services your app supports.) When presenting the view controller, you must do so using the appropriate means for the current device. On iPad, you must present the view controller in a popover. On iPhone and iPod touch, you must present it modally.
Topics
Initializing the activity view controller
init(activityItems: [Any], applicationActivities: [UIActivity]?)
Initializes a new activity view controller object that acts on the specified data.
convenience init(activityItemsConfiguration: any UIActivityItemsConfigurationReading)
Initializes a new activity view controller object that acts on the specified configuration.
class UIActivityItemsConfiguration
A configuration that allows a responder to export data through a variety of interactions.
protocol UIActivityItemsConfigurationReading
A set of methods adopted by an object so that the object can act as an activity items configuration.
Accessing the completion handler
var completionWithItemsHandler: UIActivityViewController.CompletionWithItemsHandler?
The completion handler to execute after the activity view controller is dismissed.
typealias CompletionWithItemsHandler
A completion handler to execute after the activity view controller is dismissed.
Excluding specific activity types
var excludedActivityTypes: [UIActivity.ActivityType]?
The list of services that should not be displayed.
Excluding specific sections
var excludedActivitySectionTypes: UIActivitySectionTypes
struct UIActivitySectionTypes
Elevating a prominent activity
var allowsProminentActivity: Bool
A Boolean value the system uses to elevate a system activity to make it more prominent.
Deprecated
var completionHandler: UIActivityViewController.CompletionHandler?
Deprecated
typealias CompletionHandler
Relationships
Inherits From
UIViewController
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSExtensionRequestHandlingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIActivityItemsConfigurationProvidingUIAppearanceContainerUIContentContainerUIFocusEnvironmentUIPasteConfigurationSupportingUIResponderStandardEditActionsUIStateRestoringUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Services
class UIActivity
An abstract class that you subclass to implement app-specific services.
protocol UIActivityItemSource
A set of methods that an activity view controller uses to retrieve the data items to act on.
class UIActivityItemProvider
A proxy for data that passes to an activity view controller.
https://developer.apple.com/documentation/uikit/uiactivityitemsource
- UIKit
- UIActivityItemSource
Protocol
UIActivityItemSource
A set of methods that an activity view controller uses to retrieve the data items to act on.
tvOS
protocol UIActivityItemSource : NSObjectProtocol
Overview
You can use this protocol in situations where you want to provide the data from one of your app’s existing objects instead of creating a separate UIActivityItemProvider object. When implementing this protocol, your object becomes the data provider, providing the view controller with access to the items.
Because the methods of this protocol are executed on your app’s main thread, you should avoid using this protocol in cases where the data objects might take a significant amount of time to create. When creating large data objects, consider using a UIActivityItemProvider object instead.
Topics
Getting the data items
Returns the placeholder object for the data.
Required
Returns the data object to be acted upon.
Providing information about the data items
For activities that support a subject field, returns the subject for the item.
For items that are provided as data, returns the UTI for the item.
For activities that support a preview image, returns a thumbnail preview image for the item.
Providing metadata for accelerated previews
Returns metadata to display in the preview header of the share sheet.
Relationships
Inherits From
NSObjectProtocol
Conforming Types
UIActivityItemProvider
See Also
Services
class UIActivity
An abstract class that you subclass to implement app-specific services.
class UIActivityViewController
A view controller that you use to offer standard services from your app.
class UIActivityItemProvider
A proxy for data that passes to an activity view controller.
https://developer.apple.com/documentation/uikit/uiactivityitemprovider
- UIKit
- UIActivityItemProvider
Class
UIActivityItemProvider
A proxy for data that passes to an activity view controller.
class UIActivityItemProvider
Overview
You can use a provider object in situations where you want to make data available for use by an activity but you want to delay providing that data until it’s actually needed. For example, you might use a provider object to represent a large video file that needs to be processed before it can be shared to a user’s social media account.
When you initialize a UIActivityViewController object, you can pass a provider object in addition to any other data objects. When the user selects an activity, the activity view controller adds your provider object (which is also an operation object) to an operation queue so that it can begin to gather or process the needed data.
Subclassing notes
You must subclass UIActivityItemProvider and implement its item method, which is called to generate the item data. You implement this method instead of the normal main() method you’d implement for an operation object. (The main() method calls the item method when the operation object is executed.) Your implementation of the item method should do whatever work is necessary to create and return the data.
Topics
Initializing the provider
init(placeholderItem: Any)
Initializes and returns a provider object with the specified placeholder data.
Accessing the provider attributes
var item: Any
Generates and returns the actual data-bearing object.
var placeholderItem: Any?
The placeholder object you specified at initialization time.
var activityType: UIActivity.ActivityType?
The type of the activity object that is expecting the data.
Relationships
Inherits From
Operation
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendableSendableMetatypeUIActivityItemSource
See Also
Services
class UIActivity
An abstract class that you subclass to implement app-specific services.
class UIActivityViewController
A view controller that you use to offer standard services from your app.
protocol UIActivityItemSource
A set of methods that an activity view controller uses to retrieve the data items to act on.
https://developer.apple.com/documentation/uikit/uiuseractivityrestoring)
https://developer.apple.com/documentation/uikit/uiactivity)
https://developer.apple.com/documentation/uikit/uiactivityviewcontroller)
https://developer.apple.com/documentation/uikit/uiactivityitemsource)
https://developer.apple.com/documentation/uikit/uiactivityitemprovider)
https://developer.apple.com/documentation/uikit/uiviewcontroller
- UIKit
- UIViewController
Class
UIViewController
An object that manages a view hierarchy for your UIKit app.
tvOS
@MainActor class UIViewController
Mentioned in
Displaying and managing views with a view controller
Using responders and the responder chain to handle events
Responding to memory warnings
Creating a custom container view controller
Overview
The UIViewController class defines the shared behavior that’s common to all view controllers. You rarely create instances of the UIViewController class directly. Instead, you subclass UIViewController and add the methods and properties needed to manage the view controller’s view hierarchy.
A view controller’s main responsibilities include the following:
-
Updating the contents of the views, usually in response to changes to the underlying data
-
Responding to user interactions with views
-
Resizing views and managing the layout of the overall interface
-
Coordinating with other objects — including other view controllers — in your app
A view controller is tightly bound to the views it manages and takes part in handling events in its view hierarchy. Specifically, view controllers are UIResponder objects and are inserted into the responder chain between the view controller’s root view and that view’s superview, which typically belongs to a different view controller. If none of the view controller’s views handle an event, the view controller has the option of handling the event or passing it along to the superview.
View controllers are rarely used in isolation. Instead, you often use multiple view controllers, each of which owns a portion of your app’s user interface. For example, one view controller might display a table of items while a different view controller displays the selected item from that table. Usually, only the views from one view controller are visible at a time. A view controller may present a different view controller to display a new set of views, or it may act as a container for other view controllers’ content and animate views however it wants.
Subclassing notes
Every app contains at least one custom subclass of UIViewController. More often, apps contain many custom view controllers. Custom view controllers define the overall behaviors of your app, including the app’s appearance and how it responds to user interactions. The following sections provide a brief overview of some of the tasks your custom subclass performs. For detailed information about using and implementing view controllers, see View Controller Programming Guide for iOS.
Manage views
Each view controller manages a view hierarchy, the root view of which is stored in the view property of this class. The root view acts primarily as a container for the rest of the view hierarchy. The size and position of the root view is determined by the object that owns it, which is either a parent view controller or the app’s window. The view controller that’s owned by the window is the app’s root view controller and its view is sized to fill the window.
View controllers load their views lazily. Accessing the view property for the first time loads or creates the view controller’s views. There are several ways to specify the views for a view controller:
- Specify the view controller and its views in your app’s storyboard. Storyboards are the preferred way to specify your views. With a storyboard, you specify the views and their connections to the view controller. You also specify the relationships and segues between your view controllers, which makes it easier to see and modify your app’s behavior.
To load a view controller from a storyboard, call the instantiateViewController(withIdentifier:) method of the appropriate UIStoryboard object. The storyboard object creates the view controller and returns it to your code.
- Specify the views for a view controller using a nib file. A nib file lets you specify the views of a single view controller but doesn’t let you define segues or relationships between view controllers. The nib file also stores only minimal information about the view controller itself.
To initialize a view controller object using a nib file, create your view controller class programmatically and initialize it using the init(nibName:bundle:) method. When its views are requested, the view controller loads them from the nib file.
- Specify the views for a view controller using the
loadView()method. In that method, create your view hierarchy programmatically and assign the root view of that hierarchy to the view controller’sviewproperty.
All of these techniques have the same end result, which is to create the appropriate set of views and expose them through the view property.
A view controller’s root view is always sized to fit its assigned space. For other views in your view hierarchy, use Interface Builder to specify the Auto Layout constraints that govern how each view is positioned and sized within its superview’s bounds. You can also create constraints programmatically and add them to your views at appropriate times. For more information about how to create constraints, see Auto Layout Guide.
Handle view-related notifications
When the visibility of its views changes, a view controller automatically calls its own methods so that subclasses can respond to the change. Use a method like viewIsAppearing(_:) to prepare your views to appear onscreen, and use viewWillDisappear(_:) to save changes or other state information. Use other methods to make appropriate changes.
The following image shows the possible visible states for a view controller’s views and the state transitions that can occur. Not all will callback methods are paired with only a did callback method. You need to ensure that if you start a process in a will callback method, you end the process in both the corresponding did and the opposite will callback method.
Handle view rotations
As of iOS 8, all rotation-related methods are deprecated. Instead, rotations are treated as a change in the size of the view controller’s view and are therefore reported using the viewWillTransition(to:with:) method. When the interface orientation changes, UIKit calls this method on the window’s root view controller. That view controller then notifies its child view controllers, propagating the message throughout the view controller hierarchy.
In iOS 6 and iOS 7, your app supports the interface orientations defined in your app’s Info.plist file. A view controller can override the supportedInterfaceOrientations method to limit the list of supported orientations. Typically, the system calls this method only on the root view controller of the window or a view controller presented to fill the entire screen; child view controllers use the portion of the window provided for them by their parent view controller and no longer participate directly in decisions about what rotations are supported. The intersection of the app’s orientation mask and the view controller’s orientation mask is used to determine which orientations a view controller can be rotated into.
You can override the preferredInterfaceOrientationForPresentation for a view controller that’s intended to be presented full screen in a specific orientation.
When a rotation occurs for a visible view controller, the willRotate(to:duration:), willAnimateRotation(to:duration:), and didRotate(from:) methods are called during the rotation. The viewWillLayoutSubviews() method is also called after the view is resized and positioned by its parent. If a view controller isn’t visible when an orientation change occurs, then the rotation methods are never called. However, the viewWillLayoutSubviews() method is called when the view becomes visible.
Implement a container view controller
A custom UIViewController subclass can also act as a container view controller. A container view controller manages the presentation of content of other view controllers it owns, also known as its child view controllers. A child’s view can be presented as-is or in conjunction with views owned by the container view controller.
Your container view controller subclass should declare a public interface to associate its children. The nature of these methods is up to you and depends on the semantics of the container you’re creating. You need to decide how many children can be displayed by your view controller at once, when those children are displayed, and where they appear in your view controller’s view hierarchy. Your view controller class defines what relationships, if any, are shared by the children. By establishing a clean public interface for your container, you ensure that children use its capabilities logically, without accessing too many private details about how your container implements the behavior.
Your container view controller must associate a child view controller with itself before adding the child’s root view to the view hierarchy. This allows iOS to properly route events to child view controllers and the views those controllers manage. Likewise, after it removes a child’s root view from its view hierarchy, it should disconnect that child view controller from itself. To make or break these associations, your container calls specific methods defined by the base class. These methods aren’t intended to be called by clients of your container class; they are to be used only by your container’s implementation to provide the expected containment behavior.
Here are the essential methods you might need to call:
-
addChild(_:) -
removeFromParent() -
willMove(toParent:) -
didMove(toParent:)
Manage memory
Memory is a critical resource in iOS, and view controllers provide built-in support for reducing their memory footprint at critical times. The UIViewController class provides some automatic handling of low-memory conditions through its didReceiveMemoryWarning() method, which releases unneeded memory.
Support state preservation and restoration
If you assign a value to the view controller’s restorationIdentifier property, the system may ask the view controller to encode itself when the app transitions to the background. When preserved, a view controller preserves the state of any views in its view hierarchy that also have restoration identifiers. View controllers don’t automatically save any other state. If you’re implementing a custom container view controller, you must encode any child view controllers yourself. Each child you encode must have a unique restoration identifier.
For more information about how the system determines which view controllers to preserve and restore, see App Programming Guide for iOS. To see an example of state preservation and restoration, see Restoring your app’s state.
Topics
Creating a view controller
init(nibName: String?, bundle: Bundle?)
Creates a view controller with the nib file in the specified bundle.
init?(coder: NSCoder)
Creates a view controller with data in an unarchiver.
Getting the storyboard and nib information
var storyboard: UIStoryboard?
The storyboard from which the view controller originated.
var nibName: String?
The name of the view controller’s nib file, if one was specified.
var nibBundle: Bundle?
The view controller’s nib bundle if it exists.
Managing the view
var view: UIView!
The view that the controller manages.
var viewIfLoaded: UIView?
The view controller’s view, or nil if the view isn’t yet loaded.
var isViewLoaded: Bool
A Boolean value indicating whether the view is currently loaded into memory.
func loadView()
Creates the view that the controller manages.
func viewDidLoad()
Called after the controller’s view is loaded into memory.
func loadViewIfNeeded()
Loads the view controller’s view if it’s not loaded yet.
var title: String?
A localized string that represents the view this controller manages.
var preferredContentSize: CGSize
The preferred size for the view controller’s view.
Responding to view-related events
func viewWillAppear(Bool)
Notifies the view controller that its view is about to be added to a view hierarchy.
func viewIsAppearing(Bool)
Notifies the view controller that the system is adding the view controller’s view to a view hierarchy.
func viewDidAppear(Bool)
Notifies the view controller that its view was added to a view hierarchy.
func viewWillDisappear(Bool)
Notifies the view controller that its view is about to be removed from a view hierarchy.
func viewDidDisappear(Bool)
Notifies the view controller that its view was removed from a view hierarchy.
var isBeingDismissed: Bool
A Boolean value indicating whether the view controller is in the process of being dismissed by one of its ancestors.
var isBeingPresented: Bool
A Boolean value indicating whether the view controller in the process of being presented by one of its ancestors.
var isMovingFromParent: Bool
A Boolean value indicating whether the view controller is moving from a parent view controller.
var isMovingToParent: Bool
A Boolean value indicating whether the view controller is moving to a parent view controller.
Extending the view’s safe area
Positioning content relative to the safe area
Position views so that they aren’t obstructed by other content.
var additionalSafeAreaInsets: UIEdgeInsets
Custom insets that you specify to modify the view controller’s safe area.
func viewSafeAreaInsetsDidChange()
Called to notify the view controller that the safe area insets of its root view changed.
Managing the view’s margins
Positioning content within layout margins
Position views so that they aren’t crowded by other content.
var viewRespectsSystemMinimumLayoutMargins: Bool
A Boolean value indicating whether the view controller’s view uses the system-defined minimum layout margins.
var systemMinimumLayoutMargins: NSDirectionalEdgeInsets
The minimum layout margins for the view controller’s root view.
func viewLayoutMarginsDidChange()
Called to notify the view controller that the layout margins of its root view changed.
Configuring the view’s layout behavior
var edgesForExtendedLayout: UIRectEdge
The edges that you extend for your view controller.
struct UIRectEdge
Constants that specify the edges of a rectangle.
var extendedLayoutIncludesOpaqueBars: Bool
A Boolean value indicating whether or not the extended layout includes opaque bars.
func viewWillLayoutSubviews()
Notifies the view controller that its view is about to lay out its subviews.
func viewDidLayoutSubviews()
Notifies the view controller when its view finishes laying out its subviews.
func updateViewConstraints()
Notifies the view controller when its view needs to update its constraints.
Configuring the view rotation settings
var supportedInterfaceOrientations: UIInterfaceOrientationMask
The interface orientations that the view controller supports.
var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation
The interface orientation to use when presenting the view controller.
func setNeedsUpdateOfSupportedInterfaceOrientations()
Notifies the view controller about a change in supported interface orientations or preferred interface orientation for presentation.
var prefersInterfaceOrientationLocked: Bool
Whether this view controller prefers the scene’s interface orientation to be locked when shown. The default is NO. Note that this preference may or may not be honored. See UIWindowScene.Geometry for the current state of interface orientation lock.
Beta
func setNeedsUpdateOfPrefersInterfaceOrientationLocked()
Call whenever the view controller’s preference for interface orientation lock has changed
var childViewControllerForInterfaceOrientationLock: UIViewController?
Override to return a child view controller or nil. If non-nil, that view controller’s preference for interface orientation lock will be used. If nil, self is used. Whenever the return value changes, call setNeedsUpdateOfPrefersInterfaceOrientationLocked().
Performing segues
Determines whether the segue with the specified identifier should be performed.
func prepare(for: UIStoryboardSegue, sender: Any?)
Notifies the view controller that a segue is about to be performed.
func performSegue(withIdentifier: String, sender: Any?)
Initiates the segue with the specified identifier from the current view controller’s storyboard file.
Returns an array of child view controllers to search for an unwind segue destination.
Returns the child view controller that contains the source of the unwind segue.
Called on a view controller to determine whether it responds to an unwind action.
func unwind(for: UIStoryboardSegue, towards: UIViewController)
Called when an unwind segue transitions to a new view controller.
Presenting a view controller
func show(UIViewController, sender: Any?)
Presents a view controller in a primary context.
func showDetailViewController(UIViewController, sender: Any?)
Presents a view controller in a secondary (or detail) context.
Presents a view controller modally.
Dismisses the view controller that was presented modally by the view controller.
var modalPresentationStyle: UIModalPresentationStyle
The presentation style for modal view controllers.
enum UIModalPresentationStyle
Modal presentation styles available when presenting view controllers.
var modalTransitionStyle: UIModalTransitionStyle
The transition style to use when presenting the view controller.
enum UIModalTransitionStyle
Transition styles available when presenting view controllers.
var isModalInPresentation: Bool
A Boolean value indicating whether the view controller enforces a modal behavior.
var definesPresentationContext: Bool
A Boolean value that indicates whether this view controller’s view is covered when the view controller or one of its descendants presents a view controller.
var providesPresentationContextTransitionStyle: Bool
A Boolean value that indicates whether the view controller specifies the transition style for view controllers it presents.
var disablesAutomaticKeyboardDismissal: Bool
Returns a Boolean indicating whether the current input view is dismissed automatically when changing controls.
class let showDetailTargetDidChangeNotification: NSNotification.Name
Posted when a split view controller is expanded or collapsed.
Adding a custom transition or presentation
var transitioningDelegate: (any UIViewControllerTransitioningDelegate)?
The delegate object that provides transition animator, interactive controller, and custom presentation controller objects.
var transitionCoordinator: (any UIViewControllerTransitionCoordinator)?
Returns the active transition coordinator object.
Returns the view controller that responds to the action.
var presentationController: UIPresentationController?
The presentation controller that’s managing the current view controller.
var popoverPresentationController: UIPopoverPresentationController?
The nearest popover presentation controller that is managing the current view controller.
var sheetPresentationController: UISheetPresentationController?
The sheet presentation controller for the view controller.
var activePresentationController: UIPresentationController?
The presentation controller that’s managing the view controller.
var restoresFocusAfterTransition: Bool
A Boolean value that indicates whether an item that previously was focused should again become focused when the item’s view controller becomes visible and focusable.
Customizing and resizing sheets in UIKit
Discover how to create a layered and customized sheet experience in UIKit.
Adapting to environment changes
func collapseSecondaryViewController(UIViewController, for: UISplitViewController)
Called when a split view controller transitions to a compact-width size class.
Called when a split view controller transitions to a regular-width size class.
Adjusting the interface style
var overrideUserInterfaceStyle: UIUserInterfaceStyle
The user interface style adopted by the view controller and all of its children.
var preferredUserInterfaceStyle: UIUserInterfaceStyle
The preferred interface style for this view controller.
var childViewControllerForUserInterfaceStyle: UIViewController?
The child view controller that supports the preferred user interface style.
func setNeedsUserInterfaceAppearanceUpdate()
Notifies the view controller that a change occurred that might affect the preferred interface style.
enum UIUserInterfaceStyle
Constants that indicate the interface style for the app.
Observing trait changes
protocol UITraitChangeObservable
A type that calls your code in reaction to changes in the trait environment.
Overriding trait values
var traitOverrides: UITraitOverrides
struct UITraitOverrides
Managing child view controllers in a custom container
var children: [UIViewController]
An array of view controllers that are children of the current view controller.
func addChild(UIViewController)
Adds the specified view controller as a child of the current view controller.
func removeFromParent()
Removes the view controller from its parent.
Transitions between two of the view controller’s child view controllers.
var shouldAutomaticallyForwardAppearanceMethods: Bool
Returns a Boolean value indicating whether appearance methods are forwarded to child view controllers.
func beginAppearanceTransition(Bool, animated: Bool)
Tells a child controller its appearance is about to change.
func endAppearanceTransition()
Tells a child controller its appearance has changed.
class let hierarchyInconsistencyException: NSExceptionName
Raised if the view controller hierarchy is inconsistent with the view hierarchy.
Responding to containment events
func willMove(toParent: UIViewController?)
Called just before the view controller is added or removed from a container view controller.
func didMove(toParent: UIViewController?)
Called after the view controller is added or removed from a container view controller.
Getting other related view controllers
var presentingViewController: UIViewController?
The view controller that presented this view controller.
var presentedViewController: UIViewController?
The view controller that is presented by this view controller, or one of its ancestors in the view controller hierarchy.
var parent: UIViewController?
The parent view controller of the recipient.
var splitViewController: UISplitViewController?
The nearest ancestor in the view controller hierarchy that is a split view controller.
var navigationController: UINavigationController?
The nearest ancestor in the view controller hierarchy that is a navigation controller.
var tabBarController: UITabBarController?
The nearest ancestor in the view controller hierarchy that is a tab bar controller.
Configuring a navigation interface
var navigationItem: UINavigationItem
The navigation item used to represent the view controller in a parent’s navigation bar.
var hidesBottomBarWhenPushed: Bool
A Boolean value indicating whether the toolbar at the bottom of the screen is hidden when the view controller is pushed on to a navigation controller.
func setToolbarItems([UIBarButtonItem]?, animated: Bool)
Sets the toolbar items to be displayed along with the view controller.
var toolbarItems: [UIBarButtonItem]?
The toolbar items associated with the view controller.
Configuring tab bar content
var tabBarItem: UITabBarItem!
The tab bar item that represents the view controller when added to a tab bar controller.
var tabBarObservedScrollView: UIScrollView?
The full-screen scroll view to synchronize with a scrolling tab bar.
Deprecated
Working with scrolling content
func setContentScrollView(UIScrollView?, for: NSDirectionalRectEdge)
Sets the scroll view that bars observe for the specified edge.
func setContentScrollView(UIScrollView?)
Sets the scroll view that bars observe for all edges of the view.
Returns the scroll view the view controller observes for the specified edge.
Indicating missing content
var contentUnavailableConfiguration: (any UIContentConfiguration)?
The current content-unavailable configuration of the view controller.
var contentUnavailableConfigurationState: UIContentUnavailableConfigurationState
The current configuration state of the content-unavailable view.
func setNeedsUpdateContentUnavailableConfiguration()
Requests that the system update the content-unavailable configuration for the latest state.
func updateContentUnavailableConfiguration(using: UIContentUnavailableConfigurationState)
Updates the content-unavailable configuration for the provided state.
struct UIContentUnavailableConfiguration
A content configuration for a content-unavailable view.
Supporting app extensions
var extensionContext: NSExtensionContext?
Returns the extension context of the view controller.
Coordinating with system gestures
var preferredScreenEdgesDeferringSystemGestures: UIRectEdge
The screen edges for which you want your gestures to take precedence over the system gestures.
var childForScreenEdgesDeferringSystemGestures: UIViewController?
Returns the child view controller that should be queried to see if its gestures should take precedence.
func setNeedsUpdateOfScreenEdgesDeferringSystemGestures()
Notifies the system of changes to the screen edges that defer system gestures.
var prefersHomeIndicatorAutoHidden: Bool
A Boolean that indicates whether the system is allowed to hide the visual indicator for returning to the Home Screen.
var childForHomeIndicatorAutoHidden: UIViewController?
Returns the child view controller that is consulted about its preference for displaying a visual indicator for returning to the Home screen.
func setNeedsUpdateOfHomeIndicatorAutoHidden()
Notifies UIKit that your view controller updated its preference regarding the visual indicator for returning to the Home screen.
Working with transitions
var preferredTransition: UIViewController.Transition?
An object that defines the transition animation when switching to the view controller.
class Transition
An object that defines the transition animation when switching to a new view controller.
Working with focus
var focusGroupIdentifier: String?
The identifier of the focus group that the view controller belongs to.
Managing pointer lock state
var prefersPointerLocked: Bool
A Boolean value that indicates whether the view controller prefers to lock the pointer to a specific scene.
func setNeedsUpdateOfPrefersPointerLocked()
Indicates that the view controller changed the pointer lock preference.
var childViewControllerForPointerLock: UIViewController?
A child view controller to query for the pointer lock preference.
Managing the status bar
var prefersStatusBarHidden: Bool
Specifies whether the view controller prefers the status bar to be hidden or shown.
var childForStatusBarHidden: UIViewController?
The view controller to use for determining the hidden state of the status bar.
var childForStatusBarStyle: UIViewController?
Called when the system needs the view controller to use for determining status bar style.
var preferredStatusBarStyle: UIStatusBarStyle
The preferred status bar style for the view controller.
enum UIStatusBarStyle
Constants that describe the style of the device’s status bar.
var modalPresentationCapturesStatusBarAppearance: Bool
Specifies whether a view controller, presented non-fullscreen, takes over control of status bar appearance from the presenting view controller.
var preferredStatusBarUpdateAnimation: UIStatusBarAnimation
Specifies the animation style to use for hiding and showing the status bar for the view controller.
func setNeedsStatusBarAppearanceUpdate()
Indicates to the system that the view controller status bar attributes have changed.
Managing the Touch Bar
var childViewControllerForTouchBar: UIViewController?
The child view controller that the system uses to display content in the Touch Bar.
func setNeedsTouchBarUpdate()
Tells the system to update the Touch Bar.
Accessing the available key commands
var performsActionsWhilePresentingModally: Bool
A Boolean value indicating whether the view controller performs menu-related actions.
func addKeyCommand(UIKeyCommand)
Associates the specified keyboard shortcut with the view controller.
func removeKeyCommand(UIKeyCommand)
Removes the key command from the view controller.
Adding editing behaviors to your view controller
var isEditing: Bool
A Boolean value indicating whether the view controller currently allows the user to edit the view contents.
func setEditing(Bool, animated: Bool)
Sets whether the view controller shows an editable view.
var editButtonItem: UIBarButtonItem
Returns a bar button item that toggles its title and associated state between Edit and Done.
Handling memory warnings
func didReceiveMemoryWarning()
Sent to the view controller when the app receives a memory warning.
Managing state restoration
Restoring your app’s state
Provide continuity for the user by preserving current activities.
var restorationIdentifier: String?
The identifier that determines whether the view controller supports state restoration.
var restorationClass: (any UIViewControllerRestoration.Type)?
The class responsible for recreating this view controller when restoring the app’s state.
func encodeRestorableState(with: NSCoder)
Encodes state-related information for the view controller.
func decodeRestorableState(with: NSCoder)
Decodes and restores state-related information for the view controller.
func applicationFinishedRestoringState()
Called on restored view controllers after other object decoding is complete.
Logging user interaction intervals
var interactionActivityTrackingBaseName: String?
The base name the view controller uses for logging signposts that annotate user interactions.
Supporting types
struct ViewLoading
A property wrapper that loads the view controller’s view before accessing the property.
enum UIContainerBackgroundStyle
Deprecated
Symbols that view controllers no longer support.
Structures
struct ShowDetailTargetDidChangeMessage Beta
Instance Properties
var childViewControllerForPreferredContainerBackgroundStyle: UIViewController?
var preferredContainerBackgroundStyle: UIContainerBackgroundStyle
var tab: UITab?
Instance Methods
func setNeedsUpdateOfPreferredContainerBackgroundStyle()
func setNeedsUpdateProperties()
Call to manually request a properties update for the view controller. Multiple requests may be coalesced into a single update alongside the next layout pass.
func updateProperties()
Override point for subclasses to update properties of this view controller or its view. Never call this method directly; use setNeedsUpdateProperties to schedule an update.
func updatePropertiesIfNeeded()
Forces an immediate properties update for this view controller and its view, including any view controllers and views in this subtree.
func updateTraitsIfNeeded()
Relationships
Inherits From
UIResponder
Inherited By
UIActivityViewControllerUIAlertControllerUICloudSharingControllerUICollectionViewControllerUIColorPickerViewControllerUIDocumentBrowserViewControllerUIDocumentMenuViewControllerUIDocumentPickerExtensionViewControllerUIDocumentPickerViewControllerUIDocumentViewControllerUIFontPickerViewControllerUIInputViewControllerUINavigationControllerUIPageViewControllerUIReferenceLibraryViewControllerUISearchContainerViewControllerUISearchControllerUISplitViewControllerUITabBarControllerUITableViewControllerUITextFormattingViewController
Conforms To
CVarArgCopyableCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSExtensionRequestHandlingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIActivityItemsConfigurationProvidingUIAppearanceContainerUIContentContainerUIFocusEnvironmentUIPasteConfigurationSupportingUIResponderStandardEditActionsUIStateRestoringUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Content view controllers
Build a view controller in storyboards, configure it with custom views, and fill those views with your app’s data.
Display view controllers using different techniques, and pass data between them during transitions.
class UITableViewController
A view controller that specializes in managing a table view.
class UICollectionViewController
A view controller that specializes in managing a collection view.
protocol UIContentContainer
A set of methods for adapting the contents of your view controllers to size and trait changes.
https://developer.apple.com/documentation/uikit/uitraitenvironment
- UIKit
- UITraitEnvironment
Protocol
UITraitEnvironment
A set of methods that makes the iOS interface environment available to your app.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor protocol UITraitEnvironment : NSObjectProtocol
Mentioned in
Checking the availability of 3D Touch
Overview
The iOS interface environment includes traits such as horizontal and vertical size class, display scale, and user interface idiom. To access the trait environment of an object that adopts this protocol, use the traitCollection property. The protocol also provides an overridable method that the system calls when the interface environment changes. Implement this method as part of creating an adaptive iOS app.
For more about trait collections, see UITraitCollection. For the WWDC 2014 presentation on creating adaptive interfaces in iOS, see Building Adaptive Apps with UIKit.
Topics
Accessing a trait collection
var traitCollection: UITraitCollection
The traits, such as the size class and scale factor, that describe the current environment of the object.
Required
Responding to a change in the interface environment
func traitCollectionDidChange(UITraitCollection?)
Reports changes in the iOS interface environment.
Deprecated
Relationships
Inherits From
NSObjectProtocol
Conforming Types
UIActionSheetUIActivityIndicatorViewUIActivityViewControllerUIAlertControllerUIAlertViewUIBackgroundExtensionViewUIButtonUICalendarViewUICloudSharingControllerUICollectionReusableViewUICollectionViewUICollectionViewCellUICollectionViewControllerUICollectionViewListCellUIColorPickerViewControllerUIColorWellUIContentUnavailableViewUIControlUIDatePickerUIDocumentBrowserViewControllerUIDocumentMenuViewControllerUIDocumentPickerExtensionViewControllerUIDocumentPickerViewControllerUIDocumentViewControllerUIEventAttributionViewUIFontPickerViewControllerUIImagePickerControllerUIImageViewUIInputViewUIInputViewControllerUILabelUIListContentViewUINavigationBarUINavigationControllerUIPageControlUIPageViewControllerUIPasteControlUIPickerViewUIPopoverBackgroundViewUIPopoverPresentationControllerUIPresentationControllerUIProgressViewUIReferenceLibraryViewControllerUIRefreshControlUIScreenUIScrollViewUISearchBarUISearchContainerViewControllerUISearchControllerUISearchTextFieldUISegmentedControlUISheetPresentationControllerUISliderUISplitViewControllerUIStackViewUIStandardTextCursorViewUIStepperUISwitchUITabBarUITabBarControllerUITableViewUITableViewCellUITableViewControllerUITableViewHeaderFooterViewUITextFieldUITextFormattingViewControllerUITextViewUIToolbarUIVideoEditorControllerUIViewUIViewControllerUIVisualEffectViewUIWebViewUIWindowUIWindowScene
See Also
Adaptivity
Reduce the need to manually register for trait changes when you use traits within a method or closure that supports automatic trait tracking.
Responding to changing display modes on Apple TV
Change images and resources dynamically when the screen gamut on your device changes.
class UITraitCollection
A collection of data that represents the environment for an individual element in your app’s user interface.
protocol UITraitChangeObservable
A type that calls your code in reaction to changes in the trait environment.
protocol UIMutableTraits
A mutable container of traits.
protocol UIAdaptivePresentationControllerDelegate
A set of methods that, in conjunction with a presentation controller, determine how to respond to trait changes in your app.
protocol UIContentContainer
A set of methods for adapting the contents of your view controllers to size and trait changes.
https://developer.apple.com/documentation/uikit/managing-your-app-s-life-cycle
Collection
- UIKit
- App and environment
- Managing your app’s life cycle
Managing your app’s life cycle
Respond to system notifications when your app is in the foreground or background, and handle other significant system-related events.
Overview
The current state of your app determines what it can and can’t do at any time. For example, a foreground app has someone’s attention, so it has priority over system resources, including the CPU. By contrast, a background app must do as little work as possible, and preferably nothing, because it’s offscreen. As your app changes from state to state, you must adjust its behavior accordingly.
When your app’s state changes, UIKit notifies you by calling methods of the appropriate delegate object:
-
In iOS 13 and later, use
UISceneDelegateobjects to respond to life-cycle events. -
In iOS 12 and earlier, use the
UIApplicationDelegateobject to respond to life-cycle events.
Respond to scene-based life-cycle events
UIKit delivers separate life-cycle events for each scene. A scene represents one instance of your app’s UI running on a device. A person can create multiple scenes for each app, and show and hide them separately. Because each scene has its own life cycle, each can be in a different state of execution. For example, one scene might be in the foreground while others are in the background or are suspended.
The following figure shows the state transitions for scenes. When a person or the system requests a new scene for your app, UIKit creates it and puts it in the unattached state. Person-requested scenes move quickly to the foreground, where they appear onscreen. A system-requested scene typically moves to the background so that it can process an event. For example, the system might launch the scene in the background to process a location event. When someone dismisses your app’s UI, UIKit moves the associated scene to the background state and eventually to the suspended state. UIKit can disconnect a background or suspended scene at any time to reclaim its resources, returning that scene to the unattached state.
Use scene transitions to perform the following tasks:
-
When UIKit connects a scene to your app, configure your scene’s initial UI and load the data your scene needs.
-
When transitioning to the foreground-active state, configure your UI and prepare to interact with a person. See Preparing your UI to run in the foreground.
-
Upon leaving the foreground-active state, save data and quiet your app’s behavior. See Preparing your UI to run in the background.
-
Upon entering the background state, finish crucial tasks, free up as much memory as possible, and prepare for your app snapshot. See Preparing your UI to run in the background.
-
At scene disconnection, clean up any shared resources associated with the scene.
-
In addition to scene-related events, you must also respond to the launch of your app using your
UIApplicationDelegateobject. For information about what to do at app launch, see Responding to the launch of your app.
Respond to app-based life-cycle events
In iOS 12 and earlier, UIKit delivers all life-cycle events to the UIApplicationDelegate object. The app delegate manages all of your app’s windows, including those displayed on separate screens. As a result, app state transitions affect your app’s entire UI, including content on external displays.
The following figure shows the state transitions involving the app delegate object. After launch, the system puts the app in the inactive or background state, depending on whether the UI is about to appear onscreen. When launching to the foreground, the system transitions the app to the active state automatically. After that, the state fluctuates between active and background until the app terminates.
Use app transitions to perform the following tasks:
-
At launch, initialize your app’s data structures and UI. See Responding to the launch of your app.
-
At activation, finish configuring your UI and prepare to interact with a person. See Preparing your UI to run in the foreground.
-
Upon deactivation, save data and quiet your app’s behavior. See Preparing your UI to run in the background.
-
At termination, stop all work immediately and release any shared resources. See
applicationWillTerminate(_:).
Respond to other significant events
In addition to handling life-cycle events, apps must also be prepared to handle the events listed in the following table. Use your UIApplicationDelegate object to handle most of these events. In some cases, you may also be able to handle them using notifications, allowing you to respond from other parts of your app.
| Event | Response |
|---|---|
| Memory warnings | Received when your app’s memory usage is too high. Reduce the amount of memory your app uses; see Responding to memory warnings. |
| Protected data becomes available/unavailable | Received when someone locks or unlocks their device. See applicationProtectedDataDidBecomeAvailable(_:) and applicationProtectedDataWillBecomeUnavailable(_:). |
| Handoff tasks | Received when an NSUserActivity object needs to be processed. See application(_:didUpdate:). |
| Time changes | Received for several different time changes, such as when the phone carrier sends a time update. See applicationSignificantTimeChange(_:). |
| Open URLs | Received when your app needs to open a resource. See application(_:open:options:). |
Topics
Behavioral events
Responding to memory warnings
Free up memory when asked to do so by the system.
See Also
Life cycle
Initialize your app’s data structures, prepare your app to run, and respond to any launch-time requests from the system.
class UIApplication
The centralized point of control and coordination for apps running in iOS.
protocol UIApplicationDelegate
A set of methods to manage shared behaviors for your app.
Manage multiple instances of your app’s UI simultaneously, and direct resources to the appropriate instance of your UI.
https://developer.apple.com/documentation/uikit/responding-to-the-launch-of-your-app
https://developer.apple.com/documentation/uikit/uiapplicationdelegate
https://developer.apple.com/documentation/uikit/scenes
Collection
- UIKit
- App and environment
- Scenes
API Collection
Scenes
Manage multiple instances of your app’s UI simultaneously, and direct resources to the appropriate instance of your UI.
Overview
UIKit manages each instance of your app’s UI using a UIWindowScene object. A scene contains the windows and view controllers for presenting one instance of your UI. Each scene also has a corresponding UIWindowSceneDelegate object, which you use to coordinate interactions between UIKit and your app. Scenes run concurrently with each other, sharing the same memory and app process space. As a result, a single app may have multiple scenes and scene delegate objects active at the same time.
Manage the configuration of new scenes from your UIApplicationDelegate object.
Topics
Essentials
Configure your app to appear onscreen.
Prepare your app to be suspended.
Window scenes
Supporting multiple windows on iPad
Support side-by-side instances of your app’s interface and create new windows.
protocol UIWindowSceneDelegate
Additional methods that you use to manage app-specific tasks occurring in a scene.
class UIWindowScene
A scene that manages one or more windows for your app.
class UIScene
An object that represents one instance of your app’s user interface.
protocol UISceneDelegate
The core methods you use to respond to life-cycle events occurring within a scene.
Configuration
Specifying the scenes your app supports
Tell the system about your app’s scenes, including the objects you use to manage each scene and its initial user interface.
UIApplicationSceneManifest
The information about the app’s scene-based life-cycle support.
class UISceneConfiguration
Information about the objects and storyboard for UKit to use when creating a particular scene.
class UISceneSession
An object that contains information about one of your app’s scenes.
Activation and destruction
class UISceneActivationConditions
The set of conditions that define when UIKit activates the current scene.
class ActivationRequestOptions
An object that contains information you want the system to use when activating the session associated with a scene.
class UIWindowSceneDestructionRequestOptions
An object that contains information to use when removing a window scene from your app.
class UISceneDestructionRequestOptions
An object you pass to UIKit to permanently remove a scene and its associated session from your app.
URL management
class UIOpenURLContext
A system-provided object that contains the information you need to open a single URL.
class OpenExternalURLOptions
Options you specify when asking a scene to open a URL.
Errors
enum Code
Error codes for issues with scenes.
struct UISceneError
Errors returned during the creation or management of a scene.
let UISceneErrorDomain: String
The domain for scene-related errors.
See Also
Life cycle
Respond to system notifications when your app is in the foreground or background, and handle other significant system-related events.
Initialize your app’s data structures, prepare your app to run, and respond to any launch-time requests from the system.
class UIApplication
The centralized point of control and coordination for apps running in iOS.
protocol UIApplicationDelegate
A set of methods to manage shared behaviors for your app.
https://developer.apple.com/documentation/uikit/uidevice
- UIKit
- UIDevice
Class
UIDevice
A representation of the current device.
tvOS
@MainActor class UIDevice
Overview
Use a UIDevice object to get information about the device such as assigned name, device model, and operating-system name and version. You also use the UIDevice instance to detect changes in the device’s characteristics, such as physical orientation. You get the current orientation using the orientation property or receive change notifications by registering for the orientationDidChangeNotification notification. Before using either of these techniques to get orientation data, you must enable data delivery using the beginGeneratingDeviceOrientationNotifications() method. When you no longer need to track the device orientation, call the endGeneratingDeviceOrientationNotifications() method to disable the delivery of notifications.
Similarly, you can use the UIDevice instance to obtain information and notifications about changes to the battery’s charge state (described by the batteryState property) and charge level (described by the batteryLevel property). The UIDevice instance also provides access to the proximity sensor state (described by the proximityState property). The proximity sensor detects whether the user is holding the device close to their face. Enable battery monitoring or proximity sensing only when you need it.
You can also use the playInputClick() instance method to play keyboard input clicks in custom input and keyboard accessory views.
Topics
Getting the shared device instance
class var current: UIDevice
An object that represents the current device.
Identifying the device and operating system
var name: String
The name of the device.
var systemName: String
The name of the operating system running on the device.
var systemVersion: String
The current version of the operating system.
var model: String
The model of the device.
var localizedModel: String
The model of the device as a localized string.
var userInterfaceIdiom: UIUserInterfaceIdiom
The style of interface to use on the current device.
var identifierForVendor: UUID?
An alphanumeric string that uniquely identifies a device to the app’s vendor.
Determining the available features
var isMultitaskingSupported: Bool
A Boolean value that indicates whether the current device supports multitasking.
Tracking the device orientation
var orientation: UIDeviceOrientation
The physical orientation of the device.
enum UIDeviceOrientation
Constants that describe the physical orientation of the device.
var isGeneratingDeviceOrientationNotifications: Bool
A Boolean value that indicates whether the device generates orientation notifications.
func beginGeneratingDeviceOrientationNotifications()
Begins the generation of notifications of device orientation changes.
func endGeneratingDeviceOrientationNotifications()
Ends the generation of notifications of device orientation changes.
Determining the current orientation
var isPortrait: Bool
A Boolean value that indicates whether the device is in a portrait orientation.
var isLandscape: Bool
A Boolean value that indicates whether the device is in a landscape orientation.
var isFlat: Bool
A Boolean value that indicates whether the specified orientation is face up or face down.
var isValidInterfaceOrientation: Bool
A Boolean value that indicates whether the specified orientation is one of the portrait or landscape orientations.
Getting the device battery state
var batteryLevel: Float
The battery charge level for the device.
var isBatteryMonitoringEnabled: Bool
A Boolean value that indicates whether battery monitoring is enabled.
var batteryState: UIDevice.BatteryState
The battery state for the device.
enum BatteryState
Constants that describe the battery power state of the device.
Using the proximity sensor
var isProximityMonitoringEnabled: Bool
A Boolean value that indicates whether proximity monitoring is enabled.
var proximityState: Bool
A Boolean value that indicates whether the proximity sensor is close to the user.
Playing input clicks
func playInputClick()
Plays an input click in an enabled input view.
Getting the current idiom
enum UIUserInterfaceIdiom
Constants that indicate the interface type for the device or an object that has a trait environment, such as a view and view controller.
Returns the interface idiom supported by the current device (recommended for apps that run in versions of iOS earlier than 3.2).
Deprecated
Managing notifications
All UIDevice notifications are posted by the singleton device instance returned by current.
class let batteryLevelDidChangeNotification: NSNotification.Name
A notification that posts when the battery level changes.
class let batteryStateDidChangeNotification: NSNotification.Name
A notification that posts when battery state changes.
class let orientationDidChangeNotification: NSNotification.Name
A notification that posts when the orientation of the device changes.
class let proximityStateDidChangeNotification: NSNotification.Name
A notification that posts when the state of the proximity sensor changes.
Structures
struct BatteryLevelDidChangeMessage Beta
struct BatteryStateDidChangeMessage Beta
struct OrientationDidChangeMessage Beta
struct ProximityStateDidChangeMessage Beta
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendable
See Also
Device environment
class UIStatusBarManager
An object that describes the configuration of the status bar.
https://developer.apple.com/documentation/uikit/uistatusbarmanager
- UIKit
- UIStatusBarManager
Class
UIStatusBarManager
An object that describes the configuration of the status bar.
@MainActor class UIStatusBarManager
Overview
Use a UIStatusBarManager object to get the current configuration of the status bar for its associated scene. You don’t create UIStatusBarManager objects directly. Instead, you retrieve an existing object from the statusBarManager property of a UIWindowScene object.
You don’t use this object to modify the configuration of the status bar. Instead, you set the status bar configuration individually for each of your UIViewController objects. For example, to modify the default visibility of the status bar, override the prefersStatusBarHidden property of your view controller.
Topics
Getting the status bar configuration
var isStatusBarHidden: Bool
A Boolean value that indicates whether the status bar is currently hidden.
var statusBarStyle: UIStatusBarStyle
The current appearance of the status bar.
Getting the frame rectangle
var statusBarFrame: CGRect
The frame rectangle of the status bar.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendable
See Also
Device environment
class UIDevice
A representation of the current device.
https://developer.apple.com/documentation/uikit/automatic-trait-tracking
Collection
- UIKit
- App and environment
- Automatic trait tracking
API Collection
Automatic trait tracking
Reduce the need to manually register for trait changes when you use traits within a method or closure that supports automatic trait tracking.
Overview
Automatic trait tracking is a UIKit feature that eliminates the need to manually register for trait changes when you use traits in a supported method or closure. This feature reduces the amount of code you need to write and maintain, improves performance, and encourages the best practice of using traits within the scope of the supported APIs.
Some properties aren’t appropriate to change during layoutSubviews(), for example, properties where setting the value has a side-effect of invalidating the view’s layout. Update these properties in a view’s updateProperties() method, or a view controller’s updateProperties() method. These methods support automatic trait tracking, and automatic observation tracking on objects that use the Observable() macro. Notify an object of other updates to its properties by calling setNeedsUpdateProperties() on your view, or setNeedsUpdateProperties() on your view controller. Force an object to immediately update its properties by calling updatePropertiesIfNeeded() on your view, or updatePropertiesIfNeeded() on your view controller.
A complete list of APIs that support automatic trait tracking appears below.
Topics
Views
Views support automatic trait tracking when using traits from the trait collection of the view inside any of the following methods.
func updateProperties()
Override point for subclasses to update properties of this view. Never call this method directly; use setNeedsUpdateProperties to schedule an update.
Beta
func setNeedsUpdateProperties()
Call to manually request a properties update for the view. Multiple requests may be coalesced into a single update alongside the next layout pass.
func updatePropertiesIfNeeded()
Forces an immediate properties update for this view (and its view controller, if applicable) and any subviews, including any view controllers or views in its subtree.
func layoutSubviews()
Lays out subviews.
func updateConstraints()
Updates constraints for the view.
func draw(CGRect)
Draws the view’s image within the passed-in rectangle.
struct Properties
View controllers
View controllers support automatic trait tracking for both the trait collection of the view controller and the trait collection of its view inside any of the following methods.
Override point for subclasses to update properties of this view controller or its view. Never call this method directly; use setNeedsUpdateProperties to schedule an update.
Call to manually request a properties update for the view controller. Multiple requests may be coalesced into a single update alongside the next layout pass.
Forces an immediate properties update for this view controller and its view, including any view controllers and views in this subtree.
func viewWillLayoutSubviews()
Notifies the view controller that its view is about to lay out its subviews.
func viewDidLayoutSubviews()
Notifies the view controller when its view finishes laying out its subviews.
func updateViewConstraints()
Notifies the view controller when its view needs to update its constraints.
func updateContentUnavailableConfiguration(using: UIContentUnavailableConfigurationState)
Updates the content-unavailable configuration for the provided state.
Presentation controllers
Presentation controllers support automatic trait tracking for both the trait collection of the presentation controller and the trait collection of its container view inside any of the following methods.
func containerViewWillLayoutSubviews()
Notifies the presentation controller that layout is about to begin on the views of the container view.
func containerViewDidLayoutSubviews()
Notifies the presentation controller when layout ends on the views of the container view.
Buttons
func updateConfiguration()
Updates the button configuration in response to a button state change.
var configurationUpdateHandler: UIButton.ConfigurationUpdateHandler?
A closure that executes when the button state changes.
Collection view cells
func updateConfiguration(using: UICellConfigurationState)
Updates the cell’s configuration using the current state.
var configurationUpdateHandler: UICollectionViewCell.ConfigurationUpdateHandler?
A block for handling updates to the cell’s configuration using the current state.
Table view cells
var configurationUpdateHandler: UITableViewCell.ConfigurationUpdateHandler?
Table view headers and footers
func updateConfiguration(using: UIViewConfigurationState)
Updates the view’s configuration using the current state.
var configurationUpdateHandler: UITableViewHeaderFooterView.ConfigurationUpdateHandler?
A block for handling updates to the view’s configuration using the current state.
Collection view compositional layouts
The compositional layout section provider supports automatic trait tracking when using traits from the trait collection of the layout environment in the section provider.
typealias UICollectionViewCompositionalLayoutSectionProvider
A closure that creates and returns each of the layout’s sections.
See Also
Adaptivity
Responding to changing display modes on Apple TV
Change images and resources dynamically when the screen gamut on your device changes.
class UITraitCollection
A collection of data that represents the environment for an individual element in your app’s user interface.
protocol UITraitEnvironment
A set of methods that makes the iOS interface environment available to your app.
protocol UITraitChangeObservable
A type that calls your code in reaction to changes in the trait environment.
protocol UIMutableTraits
A mutable container of traits.
protocol UIAdaptivePresentationControllerDelegate
A set of methods that, in conjunction with a presentation controller, determine how to respond to trait changes in your app.
protocol UIContentContainer
A set of methods for adapting the contents of your view controllers to size and trait changes.
https://developer.apple.com/documentation/uikit/responding-to-changing-display-modes-on-apple-tv
https://developer.apple.com/documentation/uikit/uitraitcollection
- UIKit
- UITraitCollection
Class
UITraitCollection
A collection of data that represents the environment for an individual element in your app’s user interface.
tvOS
class UITraitCollection
Mentioned in
Displaying and managing views with a view controller
Building a desktop-class iPad app
Overview
The traitCollection property of the UITraitEnvironment protocol contains traits that describe the state of various elements of the iOS user interface, such as size class, display scale, and layout direction. Together, these traits compose the UIKit trait environment.
The following classes adopt UITraitEnvironment: UIScreen, UIWindow, UIViewController, UIPresentationController, and UIView. To create an adaptive interface, write code to adjust your app’s layout according to changes in these traits. You access specific trait values using the UITraitCollection horizontalSizeClass, verticalSizeClass, displayScale, and userInterfaceIdiom properties. The UIUserInterfaceSizeClass enumeration defines the values for the horizontal and vertical size class. The display scale is a floating point number. The UIUserInterfaceIdiom enumeration defines the values for the user interface idiom.
To make your view controllers and views responsive to changes in the iOS interface environment, override the traitCollectionDidChange(_:) method from the trait environment protocol. To customize view controller animations in response to interface environment changes, override the willTransition(to:with:) method of the UIContentContainer protocol.
The following image shows the horizontal (width) and vertical (height) size classes your app can encounter when running full-screen on various devices.
For information about size classes your app encounters in Slide Over and Split View on iPad, read Slide Over and Split View Quick Start in Adopting Multitasking Enhancements on iPad.
You can create standalone trait collections to assist in matching against specific environments. The UITraitCollection class includes four specialized constructors, as well as a constructor that enables you to combine an array of trait collections, init(traitsFrom:).
One important use of standalone trait collections is to enable conditional use of images based on the current iOS interface environment. You can associate a trait collection with a UIImage instance by way of a UIImageAsset instance, as described in the overview section of UIImageAsset. For information on configuring asset catalogs graphically from within the Xcode IDE, see Managing assets with asset catalogs.
You can employ a standalone trait collection to enable a two-column split view in landscape orientation on iPhone. See the setOverrideTraitCollection(_:forChild:) method of the UIViewController class.
You can also use a standalone trait collection to customize view appearance with the appearance(for:) protocol method, as described in UIAppearance.
3D Touch and trait collections
Starting in iOS 9, you can use this class to check whether the device on which your app is running supports 3D Touch. Read the value of the forceTouchCapability property on the trait collection for any object in your app with a trait environment. For information about trait environments, see UITraitEnvironment. For the possible values of the force touch capability property, see the UIForceTouchCapability enumeration.
Because a user can turn off 3D Touch in Settings, check the value of the forceTouchCapability property in your implementation of the traitCollectionDidChange(_:) method, and adjust your code paths according to the property’s value.
Custom traits
You can create a custom trait using UITraitDefinition. You read custom traits from UITraitCollection using subscript syntax. When you define a custom trait, declare a property for the trait in an extension to UITraitCollection so that you can access your custom trait using standard property syntax.
The following example defines a property for a custom trait, and reads the trait value from a trait collection.
// ThemeTrait conforms to UITraitDefinition, with a defaultValue type of Theme. extension UITraitCollection { var theme: Theme { self[ThemeTrait.self] } }
let viewTheme = view.traitCollection.theme
Topics
Creating a trait collection
init()
Creates a trait collection whose traits are set to their default (unspecified) values.
init(userInterfaceIdiom: UIUserInterfaceIdiom)
Creates a trait collection that contains only a specified interface idiom.
init(horizontalSizeClass: UIUserInterfaceSizeClass)
Creates a trait collection that contains only a specified horizontal size class.
init(verticalSizeClass: UIUserInterfaceSizeClass)
Creates a trait collection that contains only a specified vertical size class.
init(userInterfaceStyle: UIUserInterfaceStyle)
Creates a trait collection that contains only the specified user interface style trait.
init(accessibilityContrast: UIAccessibilityContrast)
Creates a trait collection that contains only the specified accessibility contrast trait.
init(userInterfaceLevel: UIUserInterfaceLevel)
Creates a trait collection that contains only the specified user interface level trait.
init(legibilityWeight: UILegibilityWeight)
Creates a trait collection that contains only the specified legibility weight trait.
init(forceTouchCapability: UIForceTouchCapability)
Creates a trait collection that contains only a specified force touch capability trait.
init(displayScale: CGFloat)
Creates a trait collection that contains only a specified display scale.
init(displayGamut: UIDisplayGamut)
Creates a trait collection that contains only the specified display gamut trait.
init(layoutDirection: UITraitEnvironmentLayoutDirection)
Creates a trait collection that contains only the specified layout direction trait.
init(preferredContentSizeCategory: UIContentSizeCategory)
Creates a trait collection that contains only the specified content size category trait.
init(activeAppearance: UIUserInterfaceActiveAppearance)
Creates a trait collection that contains only the specified active appearance trait.
init(toolbarItemPresentationSize: UINSToolbarItemPresentationSize)
Creates a trait collection that contains only the specified toolbar item presentation size trait.
init?(coder: NSCoder)
Creates a trait collection from data in an unarchiver.
init(traitsFrom: [UITraitCollection])
Creates a trait collection that consists of traits merged from a specified array of trait collections.
Deprecated
Modifying traits
typealias TraitMutations
Getting the current traits
class var current: UITraitCollection
The trait collection for the current execution context.
Retrieving size class traits
var horizontalSizeClass: UIUserInterfaceSizeClass
The horizontal size class of the trait collection.
var verticalSizeClass: UIUserInterfaceSizeClass
The vertical size class of the trait collection.
enum UIUserInterfaceSizeClass
Constants that indicate the size class of a view.
Retrieving display-related traits
var displayScale: CGFloat
The display scale of the trait collection.
var displayGamut: UIDisplayGamut
The gamut of the current display.
enum UIDisplayGamut
Constants that indicate the gamut of the current display.
Retrieving interface-related traits
var userInterfaceStyle: UIUserInterfaceStyle
The style associated with the user interface.
enum UIUserInterfaceStyle
Constants that indicate the interface style for the app.
var userInterfaceIdiom: UIUserInterfaceIdiom
The user interface idiom of the trait collection.
enum UIUserInterfaceIdiom
Constants that indicate the interface type for the device or an object that has a trait environment, such as a view and view controller.
var userInterfaceLevel: UIUserInterfaceLevel
The elevation level of the interface.
enum UIUserInterfaceLevel
Constants that indicate the visual level for content in the window.
var layoutDirection: UITraitEnvironmentLayoutDirection
The layout direction associated with the current environment.
enum UITraitEnvironmentLayoutDirection
Constants that indicate the layout direction associated with the current environment.
var accessibilityContrast: UIAccessibilityContrast
The accessibility contrast associated with the current environment.
enum UIAccessibilityContrast
Constants that indicate the accessibility contrast setting.
var legibilityWeight: UILegibilityWeight
The font weight to apply to text.
enum UILegibilityWeight
Constants that indicate the weight to apply to text in your interface.
var activeAppearance: UIUserInterfaceActiveAppearance
A property that indicates whether the user interface has an active appearance.
enum UIUserInterfaceActiveAppearance
Constants that indicate whether the user interface has an active appearance.
var toolbarItemPresentationSize: UINSToolbarItemPresentationSize
The presentation size of a toolbar item in an AppKit toolbar.
enum UINSToolbarItemPresentationSize
Constants that specify the presentation size of a toolbar item in an AppKit toolbar.
Retrieving the force touch capability traits
var forceTouchCapability: UIForceTouchCapability
The force touch capability value of the trait collection.
enum UIForceTouchCapability
Keys that indicate the availability of 3D Touch on a device.
Retrieving content size category information
var preferredContentSizeCategory: UIContentSizeCategory
The font sizing option preferred by the user.
struct UIContentSizeCategory
Constants that indicate the preferred size of your content.
Retrieving list environment traits
var listEnvironment: UIListEnvironment
enum UIListEnvironment
Constants that indicate the style of the containing list in a collection view or table view.
Retrieving scene capture state
var sceneCaptureState: UISceneCaptureState
enum UISceneCaptureState
Retrieving dynamic range traits
var imageDynamicRange: UIImage.DynamicRange
Retrieving typesetting language traits
var typesettingLanguage: Locale.Language?
Comparing trait collections
Queries whether changing between the specified and current trait collections would affect color values.
Queries whether a trait collection contains all of another trait collection’s values.
Getting an image configuration object
var imageConfiguration: UIImage.Configuration
An image configuration object compatible with this trait collection.
Performing actions with the current traits
Executes custom code using the traits of the receiving trait collection.
Initializers
init(hdrHeadroomUsageLimit: UIHDRHeadroomUsageLimit) Beta
init(imageDynamicRange: UIImage.DynamicRange)
init(listEnvironment: UIListEnvironment)
init(sceneCaptureState: UISceneCaptureState)
init(tabAccessoryEnvironment: UITabAccessory.Environment)
Constructs a new trait collection with the given tabAccessoryEnvironment.
Beta
convenience init(typesettingLanguage: Locale.Language?)
Instance Properties
var hdrHeadroomUsageLimit: UIHDRHeadroomUsageLimit
If HDR headroom should be used for the current UI configuration. Headroom usage is disabled in certain UI configurations, such as when all an application’s windows are in the background.
var splitViewControllerLayoutEnvironment: UISplitViewController.LayoutEnvironment
The split view controller layout environment represents whether an ancestor split view controller is expanded or collapsed.
var tabAccessoryEnvironment: UITabAccessory.Environment
The tab accessory environment represents whether a given trait collection is from a view in a UITabAccessory content view.
Type Properties
static var systemTraitsAffectingColorAppearance: [UITrait]
static var systemTraitsAffectingImageLookup: [UITrait]
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSCopyingNSObjectProtocolNSSecureCodingSendableSendableMetatype
See Also
Adaptivity
Reduce the need to manually register for trait changes when you use traits within a method or closure that supports automatic trait tracking.
Responding to changing display modes on Apple TV
Change images and resources dynamically when the screen gamut on your device changes.
protocol UITraitEnvironment
A set of methods that makes the iOS interface environment available to your app.
protocol UITraitChangeObservable
A type that calls your code in reaction to changes in the trait environment.
protocol UIMutableTraits
A mutable container of traits.
protocol UIAdaptivePresentationControllerDelegate
A set of methods that, in conjunction with a presentation controller, determine how to respond to trait changes in your app.
protocol UIContentContainer
A set of methods for adapting the contents of your view controllers to size and trait changes.
https://developer.apple.com/documentation/uikit/uitraitchangeobservable-67e94
- UIKit
- UITraitChangeObservable
Protocol
UITraitChangeObservable
A type that calls your code in reaction to changes in the trait environment.
Mac CatalystvisionOS
@MainActor protocol UITraitChangeObservable
Mentioned in
Building a desktop-class iPad app
Overview
Types that conform to UITraitChangeObservable can execute your code in response to changes in their trait collection. When you register for trait changes, the system observes the specified traits, and calls your code when any of the observed traits change value.
Keep your trait registrations focused, and avoid doing work not directly relevant to updated traits. Traits may change more than once before the system updates a view, so avoid expensive work in response to trait changes. For example, use the trait change notification to call setNeedsDisplay(), and update your view in draw(_:).
UIKit cleans up registrations at the end of the object lifecycle. Unregister only in the rare situations when you need to dynamically change which traits you observe.
Topics
Observing trait changes
Registers a list of traits to observe, and calls a method on the receiving object when one of the observed traits changes.
Required
Registers a list of traits to observe and a closure to execute when one of the observed traits changes.
Registers a list of traits to observe, and calls a method on the specified target object when one of the observed traits changes.
func unregisterForTraitChanges(any UITraitChangeRegistration)
Tells the system to stop observing previously registered traits.
typealias TraitChangeHandler
A closure the system executes when observed traits change.
protocol UITraitChangeRegistration
Relationships
Conforming Types
UIActionSheetUIActivityIndicatorViewUIActivityViewControllerUIAlertControllerUIAlertViewUIBackgroundExtensionViewUIButtonUICalendarViewUICloudSharingControllerUICollectionReusableViewUICollectionViewUICollectionViewCellUICollectionViewControllerUICollectionViewListCellUIColorPickerViewControllerUIColorWellUIContentUnavailableViewUIControlUIDatePickerUIDocumentBrowserViewControllerUIDocumentMenuViewControllerUIDocumentPickerExtensionViewControllerUIDocumentPickerViewControllerUIDocumentViewControllerUIEventAttributionViewUIFontPickerViewControllerUIImagePickerControllerUIImageViewUIInputViewUIInputViewControllerUILabelUIListContentViewUINavigationBarUINavigationControllerUIPageControlUIPageViewControllerUIPasteControlUIPickerViewUIPopoverBackgroundViewUIPopoverPresentationControllerUIPresentationControllerUIProgressViewUIReferenceLibraryViewControllerUIRefreshControlUIScrollViewUISearchBarUISearchContainerViewControllerUISearchControllerUISearchTextFieldUISegmentedControlUISheetPresentationControllerUISliderUISplitViewControllerUIStackViewUIStandardTextCursorViewUIStepperUISwitchUITabBarUITabBarControllerUITableViewUITableViewCellUITableViewControllerUITableViewHeaderFooterViewUITextFieldUITextFormattingViewControllerUITextViewUIToolbarUIVideoEditorControllerUIViewUIViewControllerUIVisualEffectViewUIWebViewUIWindowUIWindowScene
See Also
Adaptivity
Reduce the need to manually register for trait changes when you use traits within a method or closure that supports automatic trait tracking.
Responding to changing display modes on Apple TV
Change images and resources dynamically when the screen gamut on your device changes.
class UITraitCollection
A collection of data that represents the environment for an individual element in your app’s user interface.
protocol UITraitEnvironment
A set of methods that makes the iOS interface environment available to your app.
protocol UIMutableTraits
A mutable container of traits.
protocol UIAdaptivePresentationControllerDelegate
A set of methods that, in conjunction with a presentation controller, determine how to respond to trait changes in your app.
protocol UIContentContainer
A set of methods for adapting the contents of your view controllers to size and trait changes.
https://developer.apple.com/documentation/uikit/uimutabletraits-13ja5
https://developer.apple.com/documentation/uikit/uiadaptivepresentationcontrollerdelegate
- UIKit
- UIAdaptivePresentationControllerDelegate
Protocol
UIAdaptivePresentationControllerDelegate
A set of methods that, in conjunction with a presentation controller, determine how to respond to trait changes in your app.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor protocol UIAdaptivePresentationControllerDelegate : NSObjectProtocol
Overview
After implementing an object that conforms to this protocol, assign that object to the delegate property of an appropriate UIPresentationController object. Your delegate can suggest a new presentation style or an entirely new view controller for displaying content. For more information about using the delegate to respond to size class changes, see UIPresentationController.
Topics
Adapting the presentation style
Asks the delegate for the presentation style to use when the specified set of traits are active.
Asks the delegate for the new presentation style to use.
Adapting the view controller
Asks the delegate for the view controller to display when adapting to the specified presentation style.
Responding to adaptive transitions
func presentationController(UIPresentationController, willPresentWithAdaptiveStyle: UIModalPresentationStyle, transitionCoordinator: (any UIViewControllerTransitionCoordinator)?)
Notifies the delegate that an adaptivity-related transition is about to occur.
func presentationControllerDidAttemptToDismiss(UIPresentationController)
Notifies the delegate that a user-initiated attempt to dismiss a view was prevented.
Asks the delegate for permission to dismiss the presentation.
func presentationControllerDidDismiss(UIPresentationController)
Notifies the delegate after a presentation is dismissed.
func presentationControllerWillDismiss(UIPresentationController)
Notifies the delegate before a presentation is dismissed.
Preparing the adaptive presentation controller
func presentationController(UIPresentationController, prepare: UIPresentationController)
Provides an opportunity to configure the adaptive presentation controller after an adaptivity change.
Relationships
Inherits From
NSObjectProtocol
Inherited By
UIPopoverPresentationControllerDelegateUISheetPresentationControllerDelegate
See Also
Adaptivity
Reduce the need to manually register for trait changes when you use traits within a method or closure that supports automatic trait tracking.
Responding to changing display modes on Apple TV
Change images and resources dynamically when the screen gamut on your device changes.
class UITraitCollection
A collection of data that represents the environment for an individual element in your app’s user interface.
protocol UITraitEnvironment
A set of methods that makes the iOS interface environment available to your app.
protocol UITraitChangeObservable
A type that calls your code in reaction to changes in the trait environment.
protocol UIMutableTraits
A mutable container of traits.
protocol UIContentContainer
A set of methods for adapting the contents of your view controllers to size and trait changes.
https://developer.apple.com/documentation/uikit/uicontentcontainer
https://developer.apple.com/documentation/uikit/uitrait-9423
https://developer.apple.com/documentation/uikit/uitraitdefinition-64c15
- UIKit
- UITraitDefinition
Protocol
UITraitDefinition
A type representing a trait in a trait collection.
Mac CatalystvisionOS
protocol UITraitDefinition
Overview
All traits contained in a UITraitCollection conform to this protocol. You can create custom traits by defining your own conforming type.
The example below defines a new trait that holds the value of an integer-based enumeration named Theme:
enum Theme: Int { case standard case monochrome }
struct ThemeTrait: UITraitDefinition { static let defaultValue = Theme.standard }
The protocol defines default implementations for name and identifier properties. Defining defaultValue is the minimum requirement to conform to this protocol. All properties you implement must be constant. UITraitDefinition defines the associated type Value which is the type of defaultValue.
The best candidates for trait values are simple value types, such as Bool, Int, Double, and enumerations with an Int raw value. You can also use lightweight structures as trait values. The system frequently tests trait values for equality, so structures need an efficient implementation of Equatable. Avoid using Swift classes as trait values.
If you use your custom trait to implement custom dynamic colors, implement affectsColorAppearance and return true. Returning true tells the system to update and redraw views automatically when the trait changes. The system responds to changes to your trait similar to changes in system traits contained in systemTraitsAffectingColorAppearance. Changes to traits that affect color appearance are more expensive, so opt in to this behavior only when necessary, and change such traits infrequently.
For each custom trait, define extensions on UIMutableTraits and UITraitCollection to enable reading and modifying your custom traits with standard property syntax. The example below shows extensions for the example Theme trait.
extension UITraitCollection { var theme: Theme { self[ThemeTrait.self] } }
extension UIMutableTraits { var theme: Theme { get { self[ThemeTrait.self] } set { self[ThemeTrait.self] = newValue } } }
A trait type serves as a unique key, identifying a trait within a trait collection. Methods such as subscript(_:) and UIPresentationController/registerForTraitChanges(_:handler:) take a trait type to identify the trait in a collection.
Traits defined in Swift aren’t automatically bridged to Objective-C. If you need to access your custom trait from both Swift and Objective-C code, define the trait in both languages. For details, see the Objective-C documentation for UITraitDefinition.
Topics
Associated Types
associatedtype Value
Required
Type Properties
static var affectsColorAppearance: Bool
Required Default implementation provided.
static var defaultValue: Self.Value
static var identifier: String
static var name: String
Relationships
Conforming Types
UITraitAccessibilityContrastUITraitActiveAppearanceUITraitDisplayGamutUITraitDisplayScaleUITraitForceTouchCapabilityUITraitHDRHeadroomUsageLimitUITraitHorizontalSizeClassUITraitImageDynamicRangeUITraitLayoutDirectionUITraitLegibilityWeightUITraitListEnvironmentUITraitPreferredContentSizeCategoryUITraitSceneCaptureStateUITraitSplitViewControllerLayoutEnvironmentUITraitTabAccessoryEnvironmentUITraitToolbarItemPresentationSizeUITraitTypesettingLanguageUITraitUserInterfaceIdiomUITraitUserInterfaceLevelUITraitUserInterfaceStyleUITraitVerticalSizeClass
See Also
Custom traits
protocol UIMutableTraits
A mutable container of traits.
typealias UITrait
https://developer.apple.com/documentation/uikit/building-a-desktop-class-ipad-app
- UIKit
- App and environment
- Building a desktop-class iPad app
Article
Building a desktop-class iPad app
Optimize your iPad app’s user experience by adopting desktop-class enhancements for multitasking with Stage Manager, document interactions, text editing, search, and more.
Overview
People can use an iPad with a Magic Keyboard and an external display to achieve desktop-class productivity. Build your app to take advantage of features that help people increase their efficiency, customize their workflows, and complete tasks more quickly. After you create a desktop-class iPad app, bring your app directly over to the Mac with minimal additional effort using Mac Catalyst. Bring your app to Apple Vision Pro using the details in Making your existing app compatible with visionOS.
Enhance the multitasking experience with Stage Manager
A great iPad app supports productivity by enabling quick, complex workflows across multiple apps with Stage Manager, which people can use to quickly switch to other open apps and windows on the side of the screen. People can also dynamically resize app windows to show many open windows side by side on the iPad or on an external display.
Follow these steps to support a great multitasking experience with Stage Manager:
-
Build your UI with scenes. A scene contains the windows and view controllers for presenting one instance of your UI. Adopt scenes as part of your app’s core infrastructure, and use them to adjust your app’s behavior at important times, such as when your scene transitions to the foreground, changes orientation, or moves to an external display. Use scenes, instead of
UIScreen, to determine which hardware display shows your UI. For more information, see Scenes. -
Support a variety of workflows with multiple app windows. Consider letting people view and interact with more than one app window at a time to enable workflows like viewing multiple documents simultaneously or quickly dragging and dropping content from one part of your app to another. Use scenes to support multiple app windows. For more information, see Supporting multiple windows on iPad.
-
Respond to window resizing. Because people who use Stage Manager can dynamically resize their iPad app windows, your app’s UI can transition through a broad range of sizes. Design your UI for flexible layout configurations, and make sure your app adapts to different window sizes quickly and smoothly. Discover your app’s environment with
UITraitCollection, and adapt to it by using Auto Layout or by registering for trait change notifications in your view controllers or views withUITraitChangeObservablein Swift orUITraitChangeRegistrationin Objective-C. -
Consider the best use of additional space that an external display provides. Support interactive resizable windows through scenes with a
windowApplicationrole, or present noninteractive content with awindowExternalDisplayNonInteractivescene. For more information, see Presenting content on a connected display. -
Test your UI on different devices, in different environments. Consider the various configurations and sizes your UI can appear in, and make sure to test your app under those conditions. For example, test under the following conditions: full screen, Split View, Slide Over, Picture in Picture (PIP), and dynamic resizing in all dimensions while using Stage Manager with an external display.
Support powerful document-editing workflows
Navigation-based apps support a specialized editor style that brings important document-editing features to the forefront and supports user customization. Navigation-based apps can also use a title menu to surface document management operations, sharing capabilities, and custom actions.
Follow these steps to support document-editing enhancements on iPad:
-
Switch to editor-style navigation for document-editing apps. Navigation-based interfaces can use the
UINavigationItem.ItemStyle.editorstyle to bring the content density and flexibility of the Mac toolbar to iPad. This style moves the title to the leading side to open up more space for important controls, so you can provide fast access to common actions with a single tap. Specify important controls usingcenterItemGroups, and enable people to customize the layout of those controls usingcustomizationIdentifier. -
Support document interactions through a title menu. Show a menu when a person taps the document’s title using
titleMenuProvider. Include standard actions like move, duplicate, and export, or implement custom actions. Add a menu header that contains document information and sharing capabilities, like share and drag and drop, usingdocumentProperties. -
Support fast document renaming. Implement
renameDelegateto show Rename in the title menu, and to surface an inline system UI for people to rename their document after tapping on the document’s title.
Simplify the text-editing process
When people use an iPad with an external keyboard, they expect full support for keyboard input, including familiar keyboard shortcuts and interactions. A smooth text-editing experience takes advantage of standard system capabilities, and tailors itself according to touch or keyboard input. To enable a productive text-editing experience, leverage system enhancements to text-editing menus, as well as Find and Replace.
Follow these steps to provide a great text-editing experience on iPad:
-
Create text-editing menus for the current input method. To create an edit menu that adjusts its presentation style according to touch or indirect input for an optimal user experience, see
UIEditMenuInteraction. -
Integrate the system Find and Replace experience into your text views. For standard system text input views like
UITextVieworWKWebView, setisFindInteractionEnabledtotrueto allow people to find and replace text using the system Find panel. For custom text view implementations, seeUIFindInteraction.
Support inline searches with suggestions
iPadOS includes an inline search UI that opens up more space for the surrounding content. Improve content discovery by taking advantage of search capabilities in your iPad app and providing search suggestions to help people navigate your content even quicker.
Follow these steps to provide a great search experience on iPad:
-
Choose the search experience that’s best for your UI. Take advantage of the inline search placement in a navigation bar to open up more space for your content. To control the search placement explicitly, set
preferredSearchBarPlacementto choose between the inline or traditional stacked search experience. -
Provide helpful search suggestions. Specify
searchSuggestionson your navigation item’s search controller to help people quickly narrow down their search. Update the search suggestions as people type. If you use a search field independently of a search controller, provide search suggestions usingsearchSuggestions.
Provide an intuitive multiple-selection experience
People who use iPad with a Magic Keyboard expect to use the trackpad to perform different types of selections and actions in your app. Leverage multiple selection to provide intuitive interactions and elevate the most relevant contextual actions.
Follow these steps to provide a great experience for multiple selection on iPad:
-
Enable lightweight multiple selection with indirect input. Allow people using indirect input methods, like a keyboard or trackpad, to select multiple items in a collection view without placing the collection view into editing mode. Opt into this behavior by setting
allowsMultipleSelection,allowsFocus, andselectionFollowsFocustotrue. -
Distinguish between selection and primary action. Primary actions allow you to distinguish between a distinct user action and a change in selection. A primary action occurs when a person selects a single cell without extending an existing selection. Implement
collectionView(_:performPrimaryActionForItemAt:)to perform actions like navigation or showing another split-view column. -
Specialize context menu options according to the number of selected items. Customize your context menus to surface different capabilities depending on whether the selection contains zero, one, or many items. Implement
collectionView(_:contextMenuConfigurationForItemsAt:point:)to support context menus for multiple selections in a collection view. If you useUIContextMenuInteractiondirectly, implementsecondaryItemIdentifiersand theUIContextMenuInteractionDelegatepreview animation methods.
Bring your iPad app to the Mac with Mac Catalyst
If your iPad app already supports a desktop-class experience, you can bring your app over to the Mac using Mac Catalyst. When you build your iPadOS app with Mac Catalyst, the system bridges certain interactions and UI elements to their counterparts in macOS.
Follow these steps to expedite the process of bringing your iPad app to the Mac with Mac Catalyst:
-
Bring your navigation bar customization to the Mac toolbar. By default,
NSToolbarautomatically hosts your navigation bar’s content when its behavioral style isUIBehavioralStyle.mac. UsebehavioralStyleto check your navigation bar’s behavioral style, andcurrentNSToolbarSectionto check where the toolbar hosts the navigation bar. You can opt out ofNSToolbarhosting your navigation bar by settingpreferredBehavioralStyletoUIBehavioralStyle.pad. -
Host custom views directly in the Mac toolbar. If you build your own
NSToolbarinstead of usingUINavigationBar, host your custom UIKit views in the toolbar by creating aNSUIViewToolbarItem. In your custom view, use thetoolbarItemPresentationSizetrait to render your content at an appropriate size depending on the toolbar’s display mode.
For more information about building an app with Mac Catalyst, see Bring an iPad App to the Mac with Mac Catalyst.
See Also
iPad
Elevating your iPad app with a tab bar and sidebar
Provide a compact, ergonomic tab bar for quick access to key parts of your app, and a sidebar for in-depth navigation.
Supporting desktop-class features in your iPad app
Enhance your iPad app by adding desktop-class features and document support.
Implement multitasking APIs to seamlessly integrate your app with iPadOS.
https://developer.apple.com/documentation/uikit/elevating-your-ipad-app-with-a-tab-bar-and-sidebar
- UIKit
- App and environment
- Elevating your iPad app with a tab bar and sidebar
Article
Elevating your iPad app with a tab bar and sidebar
Provide a compact, ergonomic tab bar for quick access to key parts of your app, and a sidebar for in-depth navigation.
Overview
In iPadOS 18 and later, the position of the tab bar moves from the bottom of the screen to float over your content at the top. This compact appearance gives you more space for your app’s content. Additionally, because it shares space with the navigation bar, it places your tabs closer to your app’s other controls.
iPadOS apps automatically receive the new tab bar appearance when you compile them for iPadOS 18 and later.
Create a tab bar
iPadOS 18 also introduces new API for creating tab bars. Create a UITabBarController and assign an array of UITab objects to its tabs property. To create a tab, call init(title:image:identifier:viewControllerProvider:). In the closure, return the view controller your app presents when someone selects the tab. If you use SF Symbols for your tab’s image, be sure to select the outline variant. The system automatically selects the correct variant (outline or filled) based on the context. Additionally, you can change a tab’s properties, such as title or image, at runtime, and the system automatically updates its appearance.
// Create the tab bar controller. let tabBarController = UITabBarController()
// Assign an array of tabs.
tabBarController.tabs = [
UITab(title: "First",
image: UIImage(systemName: "1.circle"),
identifier: "First Tab") { _ in
// Return the view controller that the tab displays.
MyFirstViewController()
},
UITab(title: "Second",
image: UIImage(systemName: "2.circle"),
identifier: "Second Tab") { _ in
// Return the view controller that the tab displays.
MySecondViewController()
},
UITab(title: "Third",
image: UIImage(systemName: "3.circle"),
identifier: "Third Tab") { _ in
// Return the view controller that the tab displays.
MyThirdViewController()
}
]
To add a search tab, create a UISearchTab instance and add it to the tabs array.
// Create a search tab. UISearchTab { _ in // Return the view controller that the tab displays. UINavigationController( rootViewController: MySearchViewController() ) }
The new iPad tab bar supports an unlimited number of items. If there isn’t enough room to display all the tabs, the system collapses any tabs that can’t fit onscreen, and lets people scroll through them. However, consider limiting your tabs to just those that fit in the tab bar. This ensures that people can access key parts of your app with one tap.
Integrate the tab bar and sidebar
Although both tab bars and sidebars play a similar navigation role in iPadOS apps, they have different strengths. A tab bar is always available and represents the key parts of your app. A sidebar provides a richer collection of possible destinations; however, people typically need to navigate
Use the new UITab and UITabGroup classes to create a hierarchy of tabs. If the tabs array contains at least one tab group, the system automatically displays the tabs as both a tab bar and a sidebar. Otherwise, it only displays the array as a tab bar. You can also explicitly define how the system displays your tabs by setting the UITabBarController object’s mode property.
// Enable the sidebar. tabBarController.mode = .tabSidebar
// Get the sidebar. let sidebar = tabBarController.sidebar
// Show the sidebar. sidebar.isHidden = false
By default, the system presents the sidebar in landscape orientation and hides it in portrait orientation; however, people can toggle between the tab bar and sidebar in either orientation. You can also programmatically show and hide the sidebar by setting its isHidden property.
Build a hierarchy of items for the sidebar
You can use UITabGroup to define a section of items in the sidebar. Provide an array of tabs for the section’s content and a view controller to display when someone selects the section from the tab bar.
let sectionOne = UITabGroup(
title: "Section 1",
image: UIImage(systemName: "1.square.fill"),
identifier: "Section one",
children:
[
UITab(
title: "Subitem A",
image: UIImage(systemName: "a.circle"),
identifier: "Section 1, item A"
) { _ in
MyFirstSubitemTabViewController()
},
UITab(
title: "Subitem B",
image: UIImage(systemName: "b.circle"),
identifier: "Section 1, item b"
) { _ in
MySecondSubitemTabViewController()
},
UITab(
title: "Subitem C",
image: UIImage(systemName: "c.circle"),
identifier: "Section 1, item C"
) { _ in
MyThirdSubitemTabViewController()
},
]) { _ in
// Return a view controller that the system displays when someone selects the section in the tab bar.
MySectionViewController()
}
The tab bar displays a tab group as a single tab item, and the sidebar displays it as a section that contains subitems. The sidebar displays top-level tab items first, followed by the sections.
You can nest a UITabGroup inside another UITabGroup to create a deeper hierarchy in the sidebar; however, consider limiting your app to two, or at most three, layers. Also, you can dynamically change a tab group’s content at runtime by modifying its children property.
Add actions to the sidebar
You can add actions to the sidebar by setting a tab group’s sidebarActions property. These actions function like buttons that you place inside the tab group.
// Create the action. let refreshAction = UIAction(title: "Refresh", image: UIImage(systemName: "arrow.clockwise")) { _ in myAction() }
// Assign the action. sectionOne.sidebarActions = [refreshAction]
To support swipe actions or context menus, assign a delegate to your sidebar that adopts the UITabBarController.Sidebar.Delegate protocol, and implement the following optional methods:
-
tabBarController(_:sidebar:leadingSwipeActionsConfigurationFor:) -
tabBarController(_:sidebar:trailingSwipeActionsConfigurationFor:) -
tabBarController(_:sidebar:contextMenuConfigurationFor:)
To support drag-and-drop operations, assign a delegate to your tab bar that adopts the UITabBarControllerDelegate protocol, and implement the tabBarController(_:tab:operationForAcceptingItemsFrom:) and tabBarController(_:tab:acceptItemsFrom:) methods.
Enable customization
With the new tab bar and sidebar, people can customize the content in both. The system provides a button to put the bars into edit mode. While editing, people can:
-
Drag items from the sidebar to the tab bar to add them to the tab bar.
-
Drag items from the tab bar to remove them from the tab bar.
-
Drag items to reorder them in the tab bar.
-
Drag items to reorder them inside their tab group.
-
Uncheck items in the sidebar to hide them. This also removes them from the tab bar.
The system automatically persists any customizations that someone makes to the bars. You can implement the tabBarController(_:displayOrderDidChangeFor:) and tabBarController(_:visibilityDidChangeFor:) delegate methods to receive notifications about the changes.
By default, only the top-level tabs appear in the tab bar. People can add or remove any tab in the sidebar, but can’t hide or reorder the items in it.
To control which items appear in the tab bar, and how people can customize them, set the UITab object’s preferredPlacement property. Conceptually, you can think of the tab bar as having three different regions:
-
Fixed tabs appear on the leading edge of the tab bar.
-
Default, optional, and movable tabs appear after the fixed tabs.
-
Pinned tabs are always visible on the trailing edge, and only show the tab’s image.
When possible, make tabs customizable so that people can choose which ones to place in the tab bar. If you have any tabs that are central to your app, consider making them fixed tabs, so that people can’t remove or move them. Use pinned tabs for prominent items, like search. Also, because pinned tabs only display the tab icon, be sure to select an image that people recognize and can easily understand.
To create an item that appears in the sidebar, but that people can’t add to the tab bar, set the preferredPlacement property to UITab.Placement.sidebarOnly. To create an item that people can add to or remove from the sidebar, set its allowsHiding property to true. If someone removes an item from the sidebar, the system also removes it from the tab bar.
// Create the tab. var customizeableItem = UITab( title: "Optional", image: UIImage(systemName: "questionmark.app"), identifier: "Optional Item" ) { _ in MyOptionalViewController() }
// Let people add and remove this item in the sidebar. customizeableItem.allowsHiding = true
// Set the item as hidden in the sidebar by default. customizeableItem.isHiddenByDefault = true
To let people reorganize items within a tab group, set the group’s allowsReordering property to true.
sectionOne.allowsReordering = true
You can also programmatically set the order of items in a tab group using its displayOrderIdentifiers property. By default, the system sets the tab group’s order based on its children property.
Use the tab bar and sidebar on other platforms
The new UITab API is also available in iOS 18, Mac Catalyst 18, tvOS 18, and visionOS 2, and later. Consider using this API to create tab bars on all UIKit-based projects.
The new tab bar and sidebar only appear on iPad. On iPhone and Apple TV, the system displays the platform’s regular tab bar. For Mac Catalyst, it displays a tab bar if the tab bar controller’s mode property is UITabBarController.Mode.tabBar, and a sidebar if it’s UITabBarController.Mode.tabSidebar.
In visionOS, the system displays the platform’s regular tabs, but a UITabGroup can display a sidebar when it displays the group’s view controller.
See Also
iPad
Building a desktop-class iPad app
Optimize your iPad app’s user experience by adopting desktop-class enhancements for multitasking with Stage Manager, document interactions, text editing, search, and more.
Supporting desktop-class features in your iPad app
Enhance your iPad app by adding desktop-class features and document support.
Implement multitasking APIs to seamlessly integrate your app with iPadOS.
https://developer.apple.com/documentation/uikit/supporting-desktop-class-features-in-your-ipad-app
- UIKit
- App and environment
- Supporting desktop-class features in your iPad app
Sample Code
Supporting desktop-class features in your iPad app
Enhance your iPad app by adding desktop-class features and document support.
Download
Xcode 15.0+
Overview
This sample project shows how to build an app that takes full advantage of the iPad’s desktop-class features like hardware keyboard and trackpad support, Stage Manager, and rich document-editing capabilities. The app is a markup document editor that allows creating, editing, previewing, and saving documents, including features like a title menu with custom actions, document renaming, Find and Replace, and more.
Choose the appropriate navigation style
Because the app allows focused viewing and editing of individual documents, it uses the UINavigationItem.ItemStyle.editor navigation style. This navigation style moves the navigation item’s title to the leading edge and opens up space in the center of the bar for common document actions. To choose the navigation style, the editor view controller assigns the navigation item’s style property.
Add center items for quick access to common actions
Center item groups are groups of controls that appear in the navigation bar to provide quick access to the app’s most important capabilities. A person can customize the navigation bar’s center items by moving, removing, or adding certain groups. To enable user customization, the app assigns a string to the navigation item’s customizationIdentifier property.
// Set a customizationIdentifier and add center item groups.
navigationItem.customizationIdentifier = "editorViewCustomization"
The editor view controller configures center items and assigns them to the navigation item’s centerItemGroups property in configureCenterItemGroups(). The editor view controller creates one fixed group that people can’t move or remove from the navigation bar for the Sync Scrolling item using creatingFixedGroup().
UIBarButtonItem(primaryAction: UIAction(title: "Sync Scrolling", image: syncScrollingImage) { [unowned self] action in syncScrolling.toggle() if let barButtonItem = action.sender as? UIBarButtonItem { barButtonItem.image = syncScrollingImage } }).creatingFixedGroup(),
Other center item groups are optional, which means people can customize their placement in the navigation bar. Optional groups that have isInDefaultCustomization set to false don’t appear in the navigation bar by default. They appear in the customization popover that a person can access by choosing the customization option in the overflow menu.
UIBarButtonItem(primaryAction: UIAction(title: "Strikethrough", image: UIImage(systemName: "strikethrough")) { [unowned self] _ in insertTag(.strikethrough) }).creatingOptionalGroup(customizationIdentifier: "strikethrough", isInDefaultCustomization: false),
Add a title menu with system and custom actions
A title menu appears when a person taps the navigation item’s title. This menu can surface actions that are relevant to the current document. To configure a title menu, the editor view controller assigns a closure to the navigation item’s titleMenuProvider property.
navigationItem.titleMenuProvider = { suggested in
let custom = [
UIMenu(title: "Export…", image: UIImage(systemName: "arrow.up.forward.square"), children: [
UIAction(title: "HTML", image: UIImage(systemName: "safari")) { [unowned self] _ in
previewView.exportAsWebArchive(named: document.localizedName, presenter: self)
},
UIAction(title: "PDF", image: UIImage(systemName: "doc.richtext")) { [unowned self] _ in
previewView.exportAsPDF(named: document.localizedName, presenter: self)
}
])
]
return UIMenu(children: suggested + custom)
}
The closure returns a menu that combines the suggested system actions and custom actions. The first set of actions in the menu are the suggested actions that the system passes in to the closure, including Move and Duplicate. The next set of actions are the custom actions that the app defines: exporting the document to HTML and PDF.
Configure a document header
A document header displays helpful information about the current document, such as its title, file type, and size. It also provides a place from which to share or drag and drop the document. To display a document header at the top of the title menu, the editor view controller assigns a UIDocumentProperties object to the navigation item’s documentProperties property.
Enable the system Find and Replace experience
The editor view supports editing the content of the document. Because the editor view is a subclass of UITextView, enabling the system Find and Replace experience takes one line of code.
// Enable Find and Replace in editor text view and register as its // delegate. editorTextView.isFindInteractionEnabled = true
Setting the isFindInteractionEnabled property enables using standard keyboard shortcuts to find text in a document and quickly replace it using the system-provided Find panel.
Enhance multiple-item selection
The outline view is a collection view that serves as a table of contents for the document, allowing for quick navigation or taking actions on the top-level tags in the document. This view supports an enhanced multiple-selection experience when a person interacts with the app using a keyboard and pointer. The outline view enables lightweight multiple selection of the tags without placing the collection view into editing mode by setting allowsMultipleSelection, allowsFocus, and selectionFollowsFocus to true.
// Enable multiple selection. collectionView.allowsMultipleSelection = true
// Enable keyboard focus. collectionView.allowsFocus = true
// Allow keyboard focus to drive selection. collectionView.selectionFollowsFocus = true
A person can use the keyboard and pointer to select tags, and perform a secondary click to open a context menu with relevant actions. The outline view presents a specialized context menu according to the number of tags in the selection by implementing collectionView(_:contextMenuConfigurationForItemsAt:point:) to return different configurations when the selection contains one or many tags.
// Action titles for a multiple-item menu. hideTitle = "Hide Selected" deleteTitle = "Delete Selected" } else { // Action titles for a single-item menu. hideTitle = "Hide" deleteTitle = "Delete" }
Perform a primary action when tapping a single item
In addition to performing a secondary click on a tag in the outline view, a person can tap a single tag to scroll to its corresponding location in the editor view. To distinguish the explicit user action of tapping one tag to navigate to that location in the document from selecting multiple tags, the outline view implements collectionView(_:performPrimaryActionForItemAt:). The system calls this method when a person taps a single tag without extending a multiple selection of tags.
func collectionView(_ collectionView: UICollectionView, performPrimaryActionForItemAt indexPath: IndexPath) {
// Get the element at the indexPath.
if let element = dataSource.itemIdentifier(for: indexPath) {
delegate?.outline(self, didChoose: element)
}
// Wait a short amount of time before deselecting the cell for visual clarity. DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { collectionView.deselectItem(at: indexPath, animated: true) } }
See Also
iPad
Building a desktop-class iPad app
Optimize your iPad app’s user experience by adopting desktop-class enhancements for multitasking with Stage Manager, document interactions, text editing, search, and more.
Elevating your iPad app with a tab bar and sidebar
Provide a compact, ergonomic tab bar for quick access to key parts of your app, and a sidebar for in-depth navigation.
Implement multitasking APIs to seamlessly integrate your app with iPadOS.
https://developer.apple.com/documentation/uikit/multitasking-on-ipad
Collection
- UIKit
- App and environment
- Multitasking on iPad
API Collection
Multitasking on iPad
Implement multitasking APIs to seamlessly integrate your app with iPadOS.
Overview
While your app’s scene runs in the foreground on iPad, other apps are likely to be running alongside it. Being aware of the environment your app may be running in and adopting the multitasking APIs are an essential part of integrating your apps with iPadOS.
The first step to creating a great multitasking experience for your users is to ensure your app’s scenes can adapt to different window sizes. Start by reading the Adaptivity and Layout section of the Human Interface Guidelines. Also, consider that your app may not be running full screen, but in a smaller window through Slide Over or Split View. Discover your app’s environment with UITraitCollection and adapt to it by using Auto Layout, or by overriding traitCollectionDidChange(_:) in your view controllers or views.
You can choose to allow multiple scenes in your app’s UI to run concurrently by setting the UIApplicationSupportsMultipleScenes property list key. Implement Scenes and read Managing your app’s life cycle for an overview of how UISceneDelegate interacts with the system multitasking events. For information on adopting the scene-based life cycle, see TN3187: Migrating to the UIKit scene-based life cycle.
Design your app’s scenes to display correctly in any interface orientation. In situations where you want to lock the app’s interface to its current orientation, call setNeedsUpdateOfPrefersInterfaceOrientationLocked(), then return true as the value of prefersInterfaceOrientationLocked, or override childViewControllerForInterfaceOrientationLock to delegate the decision to a child view controller. Implement windowScene(_:didUpdateEffectiveGeometry:) to observe orientation changes, as the system might change the interface orientation even if you signal a preference to lock it. The preference to lock the interface orientation lasts until your app stops presenting the scene, or you call setNeedsUpdateOfPrefersInterfaceOrientationLocked() again and return false as the value of prefersInterfaceOrientationLocked.
Topics
Adaptivity
class UITraitCollection
A collection of data that represents the environment for an individual element in your app’s user interface.
protocol UITraitEnvironment
A set of methods that makes the iOS interface environment available to your app.
protocol UIAdaptivePresentationControllerDelegate
A set of methods that, in conjunction with a presentation controller, determine how to respond to trait changes in your app.
protocol UIContentContainer
A set of methods for adapting the contents of your view controllers to size and trait changes.
Scene Management
Manage multiple instances of your app’s UI simultaneously, and direct resources to the appropriate instance of your UI.
Supporting multiple windows on iPad
Support side-by-side instances of your app’s interface and create new windows.
See Also
iPad
Building a desktop-class iPad app
Optimize your iPad app’s user experience by adopting desktop-class enhancements for multitasking with Stage Manager, document interactions, text editing, search, and more.
Elevating your iPad app with a tab bar and sidebar
Provide a compact, ergonomic tab bar for quick access to key parts of your app, and a sidebar for in-depth navigation.
Supporting desktop-class features in your iPad app
Enhance your iPad app by adding desktop-class features and document support.
https://developer.apple.com/documentation/uikit/uiguidedaccessrestrictiondelegate
- UIKit
- UIGuidedAccessRestrictionDelegate
Protocol
UIGuidedAccessRestrictionDelegate
A set of methods you use to add custom restrictions for the Guided Access feature in iOS.
tvOS
@MainActor protocol UIGuidedAccessRestrictionDelegate : NSObjectProtocol
Overview
Custom restrictions are represented by string identifiers provided by the developer in the guidedAccessRestrictionIdentifiers method. Each identifier represents an operation in the app that the developer wishes to allow users to restrict using Guided Access. The default for all operations is allow. Users can deny operations using the normal Guided Access user interface. See for a description of how to enable and configure Guided Access on iOS.
Apps describe their custom restrictions by implementing the textForGuidedAccessRestriction(withIdentifier:) and detailTextForGuidedAccessRestriction(withIdentifier:) methods to return appropriate localized, human-readable strings.
For example, a photo editing app might allow users to disable deleting photos. The app would return an identifier representing this restriction in its guidedAccessRestrictionIdentifiers method. It would also implement textForGuidedAccessRestriction(withIdentifier:) to provide a human-readable description of the restriction. Finally, the app would implement guidedAccessRestriction(withIdentifier:didChange:) to notice when a user indicates that they want to enable the restriction. When the app sees the state change to “deny”, it would configure itself to prevent the deletion of photos by any means. Similarly, when the app sees the state change to “allow”, it would configure itself to allow photo deletion.
Apps can use the guidedAccessRestrictionState(forIdentifier:) function to check the state of a restriction at any time.
Topics
Identifying custom Guided Access restrictions
var guidedAccessRestrictionIdentifiers: [String]?
An array of strings identifying custom restrictions.
Required
Provides a succinct description of the restriction for the specified identifier.
Provides more detailed information about the restriction for the specified identifier.
Implementing restrictions
func guidedAccessRestriction(withIdentifier: String, didChange: UIAccessibility.GuidedAccessRestrictionState)
Tells the delegate that the restriction associated with the identifier has changed state.
enum GuidedAccessRestrictionState
Constants that describe the state of a restriction, either allow or deny.
Relationships
Inherits From
NSObjectProtocol
See Also
Guided Access
Returns the restriction state for the specified guided access restriction.
https://developer.apple.com/documentation/uikit/uiaccessibility/guidedaccessrestrictionstate(foridentifier:)
https://developer.apple.com/documentation/uikit/updating-your-app-from-32-bit-to-64-bit-architecture
Collection
- UIKit
- App and environment
- Updating your app from 32-bit to 64-bit architecture
Updating your app from 32-bit to 64-bit architecture
Ensure that your app behaves as expected by adapting it to support later versions of the operating system.
Overview
In iOS 11 and later, all apps use the 64-bit architecture. If your app targets an earlier version of iOS, you must update it to run on later versions.
Update your app to the latest SDK
Begin by updating your existing app to iOS 11 or later. By updating your app first, you can remove deprecated code paths, address any compiler warnings, and search your code for specific 64-bit issues.
-
Install the latest version of Xcode and open your project. Xcode prompts you to modernize the project. Modernizing adds new warnings and errors that are important when compiling your app for 64-bit architecture.
-
Update your project settings to support the latest version of iOS. You can’t build a 64-bit project if it targets an iOS version earlier than iOS 5.1.
-
Change the Architectures build setting in your project to Standard Architectures.
-
Update your app to support the 64-bit runtime environment. The new compiler warnings and errors help guide you through this process.
-
Test your app on actual 64-bit hardware. Don’t rely on the Simulator app. Although it can be helpful during development, some changes, such as the function-calling conventions, are visible only when your app is running on a device.
-
Tune your app’s memory performance by using Instruments.
Audit your code
It’s critical that you review your code for proper pointer usage. Assumptions in pointer sizes can lead to erratic behavior and even crashes. Focus on the following areas:
-
Updating data structures. Eliminate assumptions about type size and alignment in structures, and use explicit data types.
-
Auditing pointer usage. Adhere to proper casting behaviors and review your methods for allocating memory.
-
Managing functions and function pointers . Use function prototypes for safety, and review the calling of functions that have variable-length argument lists.
With pointer usage addressed, your app should be stable and you can focus on performance and optimize accordingly:
-
Optimizing memory performance. Establish performance tests that measure your use of memory in the context of 64-bit runtime.
-
Verifying mathematical calculations. Verify signed values in math operations to ensure accurate results, and review your use of bit mask operations.
Topics
Memory and pointer access
Updating data structures
Review your app’s data design and update it to conform with 64-bit architecture.
Auditing pointer usage
Ensure that the pointers in your code are safe for the 64-bit runtime.
Managing functions and function pointers
Ensure that your code correctly handles functions, function pointers, and Objective-C messages.
Performance and accuracy
Optimizing memory performance
Measure the impact of the 64-bit runtime on your app’s memory usage.
Verifying mathematical calculations
Ensure the accuracy of your math operations in 64-bit architecture.
See Also
Architecture
Creates the application object and the application delegate and sets up the event cycle.
https://developer.apple.com/documentation/uikit/uiapplicationmain(::::)-1yub7
-1yub7#app-main)
- UIKit
- UIApplicationMain(_:_:_:_:)
Function
UIApplicationMain(_:_:_:_:)
Creates the application object and the application delegate and sets up the event cycle.
iOSiPadOSMac CatalysttvOSvisionOS
func UIApplicationMain( _ argc: Int32,
_ principalClassName: String?, _ delegateClassName: String?
Parameters
argc
The count of arguments in argv; this usually is the corresponding parameter to main.
argv
A variable list of arguments; this usually is the corresponding parameter to main.
principalClassName
The name of the UIApplication class or subclass. If you specify nil, UIApplication is assumed.
delegateClassName
The name of the class from which the application delegate is instantiated. If principalClassName designates a subclass of UIApplication, you may designate the subclass as the delegate; the subclass instance receives the application-delegate messages. Specify nil if you load the delegate object from your application’s main nib file.
Return Value
Even though an integer return type is specified, this function never returns. When users exits an iOS app by pressing the Home button, the application moves to the background.
Mentioned in
About the app launch sequence
Discussion
This function instantiates the application object from the principal class and instantiates the delegate (if any) from the given class and sets the delegate for the application. It also sets up the main event loop, including the application’s run loop, and begins processing events. If the application’s Info.plist file specifies a main nib file to be loaded, by including the NSMainNibFile key and a valid nib file name for the value, this function loads that nib file.
Despite the declared return type, this function never returns.
See Also
Architecture
Ensure that your app behaves as expected by adapting it to support later versions of the operating system.
https://developer.apple.com/documentation/uikit/uiviewcontroller)
https://developer.apple.com/documentation/uikit/uitraitenvironment)
https://developer.apple.com/documentation/uikit/managing-your-app-s-life-cycle)
https://developer.apple.com/documentation/uikit/responding-to-the-launch-of-your-app)
https://developer.apple.com/documentation/uikit/uiapplicationdelegate)
https://developer.apple.com/documentation/uikit/scenes)
https://developer.apple.com/documentation/uikit/uidevice)
https://developer.apple.com/documentation/uikit/uistatusbarmanager)
https://developer.apple.com/documentation/uikit/automatic-trait-tracking)
https://developer.apple.com/documentation/uikit/responding-to-changing-display-modes-on-apple-tv)
https://developer.apple.com/documentation/uikit/uitraitcollection)
https://developer.apple.com/documentation/uikit/uitraitchangeobservable-67e94)
https://developer.apple.com/documentation/uikit/uimutabletraits-13ja5)
https://developer.apple.com/documentation/uikit/uiadaptivepresentationcontrollerdelegate)
https://developer.apple.com/documentation/uikit/uicontentcontainer)
https://developer.apple.com/documentation/uikit/uitrait-9423)
https://developer.apple.com/documentation/uikit/uitraitdefinition-64c15)
https://developer.apple.com/documentation/uikit/building-a-desktop-class-ipad-app)
https://developer.apple.com/documentation/uikit/elevating-your-ipad-app-with-a-tab-bar-and-sidebar)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/supporting-desktop-class-features-in-your-ipad-app)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/multitasking-on-ipad)
https://developer.apple.com/documentation/uikit/uiguidedaccessrestrictiondelegate)
https://developer.apple.com/documentation/uikit/uiaccessibility/guidedaccessrestrictionstate(foridentifier:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/updating-your-app-from-32-bit-to-64-bit-architecture)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplicationmain(::::)-1yub7)
https://developer.apple.com/documentation/uikit/requesting-access-to-protected-resources
- UIKit
- Protecting the User’s Privacy
- Requesting access to protected resources
Article
Requesting access to protected resources
Provide a purpose string that explains to a person why you need access to protected resources on their device.
Overview
Modern devices collect and store a wealth of sensitive information about people who use them. Many apps rely on this kind of data, and the device hardware that generates it, to do useful work. For example, a navigation app needs a person’s GPS coordinates to locate the person on a map. But not all apps need access to all data. The same navigation app doesn’t need access to a person’s health history, camera interface, or Bluetooth peripherals.
Ensure your app accesses only what it needs to do its job. To support this principle, Apple’s operating systems restrict access to protected data and resources by default. Apps can request access on a case-by-case basis, providing an explanation for why they need access. The person who uses the app decides whether to grant or deny the request.
Provide a purpose string
The first time your app attempts to access a protected resource, the system prompts the person using the app for permission. In the following example, an iOS app called FoodDeliveryApp, which provides a food delivery service, generates a prompt requesting access to the person’s location:
If the person grants permission, the system remembers the person’s choice and doesn’t prompt again. If the person denies permission, the access attempt that initiates the prompt, and any further attempts, fail in a resource-specific way. For the particular case of access to location data, the person can choose to allow access for one session only by tapping Allow Once.
The system automatically generates the prompt’s title, which includes the name of your app. You supply a message called a purpose string or a usage description — in this case, “Your location allows you to view restaurants in delivery range of your address.” — to indicate the reason that your app needs the access. Accurately and concisely explaining to the person why your app needs access to sensitive data, typically in one complete sentence, lets the person make an informed decision and improves the chances that they grant access.
You provide a purpose string by setting a string value for a resource-specific key that you add to your app’s Information Property List file. The message in the image above, for example, is a string associated with the NSLocationWhenInUseUsageDescription key. Modify your Info.plist file using the property list editor in Xcode.
Always provide a valid purpose string in the Info.plist file if your app uses a protected resource. If you don’t, attempts to access the resource fail, and might even cause your app to crash.
If your app supports multiple locales, in addition to providing a purpose string in the Info.plist file, localize it, and place the localized string in the InfoPlist.strings files for each locale you want to support.
Adhere to the requirements for purpose strings
To give people useful, concise information about why you’re requesting access to protected resources, make sure each purpose string you provide is valid by checking the following:
-
The purpose string isn’t blank and doesn’t consist solely of whitespace characters.
-
The purpose string is shorter than 4,000 bytes. Typical purpose strings are one complete sentence, but you can provide additional information to help a person make the right decision about sharing personal information.
-
The purpose string has the proper type that the corresponding key requires, typically a string.
-
The purpose string provides a description that’s accurate, meaningful, and specific about why the app needs to access the protected resource.
Adhere to these requirements for every purpose string in the Info.plist file and locale-specific InfoPlist.strings files.
App Review checks for the use of protected resources, and rejects apps that contain code accessing those resources without a purpose string. For example, an app accessing location might receive the following information from App Review about the requirement that an NSLocationWhenInUseUsageDescription key be present:
ITMS-90683: Missing purpose string in Info.plist. Your app’s code references one or more APIs that access sensitive user data, or the app has one or more entitlements that permit such access. The Info.plist file for the "{app-bundle-path}" bundle should contain a NSLocationWhenInUseUsageDescription key with a user-facing purpose string explaining clearly and completely why your app needs the data. If you’re using external libraries or SDKs, they may reference APIs that require a purpose string. While your app might not use these APIs, a purpose string is still required. For details, visit:
To resolve this issue, provide a purpose string that explains why the app needs access to this sensitive information, or remove the code that’s accessing the resource.
Check for authorization
Many system frameworks that provide access to protected resources have dedicated APIs for checking and requesting authorization to use those resources. This model allows you to adjust your app’s behavior depending on the current access it has. For example, if a person denies your app permission to do something, you can remove related elements from your user interface.
Because a person can change authorization at any time using Settings, always check the authorization status of a feature before accessing it. In cases without a dedicated API, prepare your app to gracefully handle access failures.
Reset authorization access
When your app attempts to access a protected resource after its first attempt, the system remembers the person’s permission choice and doesn’t prompt again. To prompt the person again, you need to reset access to these resources on your device or system.
$ tccutil reset AppleEvents
This command resets authorization access for all apps using the protected resource. You can similarly specify Camera, Calendar, Reminders, or other services to reset them individually.
See Also
Supporting Privacy
Encrypting Your App’s Files
Protect the user’s data in iOS by encrypting it on disk.
https://developer.apple.com/documentation/uikit/encrypting-your-app-s-files
- UIKit
- Protecting the User’s Privacy
- Encrypting Your App’s Files
Article
Encrypting Your App’s Files
Protect the user’s data in iOS by encrypting it on disk.
Overview
Data protection is an iOS feature that you use to secure your app’s files and prevent unauthorized access to them. Data protection is enabled automatically when the user sets an active passcode for the device. You read and write your files normally, but the system encrypts and decrypts your content behind the scenes. The encryption and decryption processes are automatic and hardware accelerated.
You specify the level of data protection that you want to apply to each of your files. There are four levels available, each of which determines when you may access the file. If you do not specify a protection level when creating a file, iOS applies the default protection level automatically.
-
No protection. The file is always accessible.
-
Complete until first user authentication. (Default) The file is inaccessible until the first time the user unlocks the device. After the first unlocking of the device, the file remains accessible until the device shuts down or reboots.
-
Complete unless open. You can open existing files only when the device is unlocked. If you have a file already open, you may continue to access that file even after the user locks the device. You can also create new files and access them while the device is locked or unlocked.
-
Complete. The file is accessible only when the device is unlocked.
To create and encrypt a new file in one step, construct a data object with the file’s contents and call the write(to:options:) method. When calling the method, specify the data protection option that you want applied to the file. The following code shows an example of how to write out the contents of a Data instance to a file and encrypt it using the complete protection level.
do { try data.write(to: fileURL, options: .completeFileProtection) } catch { // Handle errors. }
To change the data protection level of an existing file, use the setResourceValue(_:forKey:) method of NSURL. When calling this method, assign the new data protection option to the fileProtectionKey resource key. The following code shows an example that adds this key to an existing file.
do { try (fileURL as NSURL).setResourceValue( URLFileProtection.complete, forKey: .fileProtectionKey) } catch { // Handle errors. }
Manage Your Access to Encrypted Files
Depending on a file’s protection level, attempts to read or write its contents could fail when the user subsequently locks the device. To ensure that your app is able to access files, do the following:
-
Choose the right data protection level for your needs.
-
Use the app delegate’s
applicationProtectedDataWillBecomeUnavailable(_:)andapplicationProtectedDataDidBecomeAvailable(_:)methods to close and reopen files with thecompleteFileProtectionlevel.
Assign the complete protection level to files that your app accesses only when it is in the foreground. If your app supports background capabilities, such as handling location updates, assign a different protection level for files that you might access while in the background. For example, a fitness app might use the complete unless open protection level on a file that it uses to log location events in the background.
Files containing personal information about the user, or files created directly by the user, always warrant the strongest level of protection. Assign the complete protection level to user data files and manage access to those files using the app delegate methods. The app delegate methods give you time to close the files before they become inaccessible to your app.
See Also
Supporting Privacy
Requesting access to protected resources
Provide a purpose string that explains to a person why you need access to protected resources on their device.
https://developer.apple.com/documentation/uikit/uidevice/identifierforvendor
- UIKit
- UIDevice
- identifierForVendor
Instance Property
identifierForVendor
An alphanumeric string that uniquely identifies a device to the app’s vendor.
tvOS
@MainActor var identifierForVendor: UUID? { get }
Discussion
The value of this property is the same for apps that come from the same vendor running on the same device. A different value is returned for apps on the same device that come from different vendors, and for apps on different devices regardless of vendor.
Normally, the vendor is determined by data provided by the App Store. If the app wasn’t installed from the app store (such as enterprise apps and apps still in development), then a vendor identifier is calculated based on the app’s bundle ID. The bundle ID is assumed to be in reverse-DNS format.
-
In iOS 6, the first two components of the bundle ID are used to generate the vendor ID. If the bundle ID only has a single component, then the entire bundle ID is used.
-
In IOS 7, all components of the bundle except for the last component are used to generate the vendor ID. If the bundle ID only has a single component, then the entire bundle ID is used.
The following table shows a collection of bundle IDs and which portions of the bundle ID the system uses to calculate the vendor ID.
| Bundle ID | iOS 6.x | iOS 7.x |
|---|---|---|
| Com.example.app1 | Com.example.app1 | Com.example.app1 |
| Com.example.app2 | Com.example.app2 | Com.example.app2 |
| Com.example.app.app1 | Com.example.app.app1 | Com.example.app.app1 |
| Com.example.app.app2 | Com.example.app.app2 | Com.example.app.app2 |
| Example | Example | Example |
For example, com.example.app1 and com.example.app2 would appear to have the same vendor ID.
If the value is nil, wait and get the value again later. This happens, for example, after the device has been restarted but before the user has unlocked the device.
The value in this property remains the same while the app (or another app from the same vendor) is installed on the iOS device. The value changes when the user deletes all of that vendor’s apps from the device and subsequently reinstalls one or more of them. The value can also change when installing test builds using Xcode or when installing an app on a device using ad-hoc distribution. Therefore, if your app stores the value of this property anywhere, you should gracefully handle situations where the identifier changes.
See Also
Identifying the device and operating system
var name: String
The name of the device.
var systemName: String
The name of the operating system running on the device.
var systemVersion: String
The current version of the operating system.
var model: String
The model of the device.
var localizedModel: String
The model of the device as a localized string.
var userInterfaceIdiom: UIUserInterfaceIdiom
The style of interface to use on the current device.
https://developer.apple.com/documentation/uikit/requesting-access-to-protected-resources).
https://developer.apple.com/documentation/uikit/encrypting-your-app-s-files).
https://developer.apple.com/documentation/uikit/uidevice/identifierforvendor)
https://developer.apple.com/documentation/uikit/requesting-access-to-protected-resources)
https://developer.apple.com/documentation/uikit/encrypting-your-app-s-files)
https://developer.apple.com/documentation/uikit/uicontrol
- UIKit
- UIControl
Class
UIControl
The base class for controls, which are visual elements that convey a specific action or intention in response to user interactions.
tvOS
@MainActor class UIControl
Mentioned in
Displaying and managing views with a view controller
Overview
Controls implement elements such as buttons and sliders, which your app can use to facilitate navigation, gather user input, or manipulate content. Controls use the target-action mechanism to report user interactions to your app.
You don’t create instances of this class directly. The UIControl class is a subclassing point that you extend to implement custom controls. You can also subclass existing control classes to extend or modify their behaviors. For example, you might override the methods of this class to track touch events yourself or to determine when the state of the control changes.
A control’s state determines its appearance and its ability to support user interactions. Controls can be in one of several states, which the UIControl.State type defines. You can change the state of a control programmatically according to your app’s needs. For example, you might disable a control to prevent the user from interacting with it. User interactions can also change the state of a control.
Respond to user interaction
The target-action mechanism simplifies the code that you write to use controls in your app. Instead of writing code to track touch events, you write action methods to respond to control-specific events. For example, you might write an action method that responds to changes in the value of a slider. The control handles all the work of tracking incoming touch events and determining when to call your methods.
When adding an action method to a control, you specify both the action method and an object that defines that method to the addTarget(_:action:for:) method. (You can also configure the target and action of a control in Interface Builder.) The target object can be any object, but it’s typically the view controller’s root view that contains the control. If you specify nil for the target object, the control searches the responder chain for an object that defines the specified action method.
The signature of an action method takes one of three forms. The sender parameter corresponds to the control that calls the action method, and the event parameter corresponds to the UIEvent object that triggered the control-related event.
@IBAction func doSomething() @IBAction func doSomething(sender: UIButton) @IBAction func doSomething(sender: UIButton, forEvent event: UIEvent)
- (IBAction)doSomething;
- (IBAction)doSomething:(id)sender;
- (IBAction)doSomething:(id)sender forEvent:(UIEvent*)event;
The system calls action methods when the user interacts with the control in specific ways. The UIControl.Event type defines the types of user interactions that a control can report and those interactions mostly correlate to specific touch events within the control. When configuring a control, you must specify which events trigger the calling of your method. For a button control, you might use the touchDown or touchUpInside event to trigger calls to your action method. For a slider, you might care only about changes to the slider’s value, so you might choose to attach your action method to valueChanged events.
When a control-specific event occurs, the control calls any associated action methods immediately. The current UIApplication object dispatches action methods and finds an appropriate object to handle the message, following the responder chain, if necessary. For more information about responders and the responder chain, see Event Handling Guide for UIKit Apps.
Configure control attributes in Interface Builder
The following table lists the attributes for instances of the UIControl class.
Support localization
Because UIControl is an abstract class, you don’t internationalize it specifically. However, you do internationalize the content of subclasses like UIButton. For information about internationalizing a specific control, see the reference for that control.
Make controls accessible
Controls are accessible by default. To be useful, an accessible user interface element must provide accurate and helpful information about its screen position, name, behavior, value, and type. This is the information VoiceOver speaks to users. Users who are blind or have low vision can rely on VoiceOver to help them use their devices.
Controls support the following accessibility attributes:
-
Label. A short, localized word or phrase that succinctly describes the control or view, but doesn’t identify the element’s type. Examples are Add and Play.
-
Traits. A combination of one or more individual traits, each of which describes a single aspect of an element’s state, behavior, or usage. For example, you might use a combination of the Keyboard Key and the Selected traits to describe an element that behaves like a keyboard key and that’s in a selected state.
-
Hint. A brief, localized phrase that describes the results of an action on an element. Examples are Adds a title and Opens the shopping list.
-
Frame. The frame of the element in screen coordinates, which the
CGRectstructure specifies for an element’s screen location and size. -
Value. The current value of an element when the label doesn’t represent the value. For example, the label for a slider might be Speed, but its current value might be 50%.
The UIControl class provides default content for the value and frame attributes. Many controls automatically enable additional specific traits as well. You can configure other accessibility attributes programmatically or with the Identity inspector in Interface Builder.
For more information about accessibility attributes, see Accessibility Programming Guide for iOS.
Subclassing notes
Subclassing UIControl gives you access to the built-in target-action mechanism and simplified event-handling support. You can subclass existing controls and modify their behavior in one of two ways:
-
Override the
sendAction(_:to:for:)method of an existing subclass to observe or modify the dispatching of action methods to the control’s associated targets. You might use this method to modify the dispatch behavior for the specified object, selector, or event. -
Override the
beginTracking(_:with:),continueTracking(_:with:),endTracking(_:with:), andcancelTracking(with:)methods to track touch events occurring in the control. You can use the tracking information to perform additional actions. Always use these methods to track touch events instead of the methods that theUIResponderclass defines.
If you subclass UIControl directly, your subclass is responsible for setting up and managing your control’s visual appearance. Use the methods for tracking events to update your control’s state and to send an action when the control’s value changes.
Topics
Creating a control
convenience init(frame: CGRect, primaryAction: UIAction?)
Creates a control with the specified frame and primary action.
init(frame: CGRect)
Creates a control with the specified frame.
init?(coder: NSCoder)
Creates a control from data in an unarchiver.
Managing state
var state: UIControl.State
The state of the control, specified as a bit mask value.
struct State
Constants describing the state of a control.
var isEnabled: Bool
A Boolean value indicating whether the control is in the enabled state.
var isSelected: Bool
A Boolean value indicating whether the control is in the selected state.
var isHighlighted: Bool
A Boolean value indicating whether the control draws a highlight.
Specifying content alignment
var contentVerticalAlignment: UIControl.ContentVerticalAlignment
The vertical alignment of content within the control’s bounds.
enum ContentVerticalAlignment
Constants for specifying the vertical alignment of content (text and images) in a control.
var contentHorizontalAlignment: UIControl.ContentHorizontalAlignment
The horizontal alignment of content within the control’s bounds.
var effectiveContentHorizontalAlignment: UIControl.ContentHorizontalAlignment
The horizontal alignment currently in effect for the control.
enum ContentHorizontalAlignment
The horizontal alignment of content (text and images) within a control.
Managing the control’s targets and actions
func addTarget(Any?, action: Selector, for: UIControl.Event)
Associates a target object and action method with the control.
func removeTarget(Any?, action: Selector?, for: UIControl.Event)
Stops the delivery of events to the specified target object.
Returns all target objects associated with the control.
func addAction(UIAction, for: UIControl.Event)
func removeAction(UIAction, for: UIControl.Event)
func removeAction(identifiedBy: UIAction.Identifier, for: UIControl.Event)
Returns the actions performed on a target object when the specified event occurs.
var allControlEvents: UIControl.Event
Returns the events for which the control has associated actions.
Triggering actions
func performPrimaryAction()
Calls the method associated with the control’s primary action.
func sendAction(UIAction)
func sendAction(Selector, to: Any?, for: UIEvent?)
Calls the specified action method.
func sendActions(for: UIControl.Event)
Calls the action methods associated with the specified events.
Tracking touches and redrawing controls
Notifies the control when a touch event enters the control’s bounds.
Notifies the control when a touch event for the control updates.
func endTracking(UITouch?, with: UIEvent?)
Notifies the control when a touch event associated with the control ends.
func cancelTracking(with: UIEvent?)
Notifies the control to cancel tracking related to the specified event.
var isTracking: Bool
A Boolean value that indicates whether the control is currently tracking touch events.
var isTouchInside: Bool
A Boolean value that indicates whether a tracked touch event is currently inside the control’s bounds.
Managing context menus
Adding context menus in your app
Provide quick access to useful actions by adding context menus to your iOS app.
var contextMenuInteraction: UIContextMenuInteraction?
A context menu interaction for the control.
var isContextMenuInteractionEnabled: Bool
A Boolean value that determines whether the control enables its context menu interaction.
var showsMenuAsPrimaryAction: Bool
A Boolean value that determines whether the context menu interaction is the control’s primary action.
func contextMenuInteraction(UIContextMenuInteraction, willDisplayMenuFor: UIContextMenuConfiguration, animator: (any UIContextMenuInteractionAnimating)?)
func contextMenuInteraction(UIContextMenuInteraction, willEndFor: UIContextMenuConfiguration, animator: (any UIContextMenuInteractionAnimating)?)
Showing tooltips
Show tooltips in your iPhone and iPad apps running on a Mac with Apple silicon, or your app built with Mac Catalyst.
var toolTip: String?
The default text to display in the control’s tooltip.
var toolTipInteraction: UIToolTipInteraction?
The tooltip interaction associated with the control.
Constants
struct Event
Constants describing the types of events possible for controls.
Instance Properties
var isSymbolAnimationEnabled: Bool
A Boolean value that indicates whether symbol effects animate.
Relationships
Inherits From
UIView
Inherited By
UIButtonUIColorWellUIDatePickerUIPageControlUIPasteControlUIRefreshControlUISegmentedControlUISliderUIStepperUISwitchUITextField
Conforms To
CALayerDelegateCVarArgCopyableCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUIContextMenuInteractionDelegateUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Controls
Responding to control-based events using target-action
Handle user input by connecting buttons, sliders, and other controls to your app’s code using the target-action design pattern.
class UIButton
A control that executes your custom code in response to user interactions.
class UIColorWell
A control that displays a color picker.
class UIDatePicker
A control for inputting date and time values.
class UIPageControl
A control that displays a horizontal series of dots, each of which corresponds to a page in the app’s document or other data-model entity.
class UISegmentedControl
A horizontal control that consists of multiple segments, each segment functioning as a discrete button.
class UISlider
A control for selecting a single value from a continuous range of values.
class UIStepper
A control for incrementing or decrementing a value.
class UISwitch
A control that offers a binary choice, such as on/off.
https://developer.apple.com/documentation/uikit/collection-views
Collection
- UIKit
- Views and controls
- Collection views
API Collection
Collection views
Display nested views using a configurable and highly customizable layout.
Overview
A collection view manages an ordered set of content, such as the grid of photos in the Photos app, and presents it visually.
Collection views are a collaboration between many different objects, including:
-
Cells. A cell provides the visual representation for each piece of your content.
-
Layouts. A layout defines the visual arrangement of the content in the collection view.
-
Your data source object. This object adopts the
UICollectionViewDataSourceprotocol and provides the data for the collection view. -
Your delegate object. This object adopts the
UICollectionViewDelegateprotocol and manages user interactions with the collection view’s contents, like selection and highlighting. -
Collection view controller. You typically use a
UICollectionViewControllerobject to manage a collection view. You can use other view controllers too, but a collection view controller is required for some collection-related features to work.
Topics
View
class UICollectionView
An object that manages an ordered collection of data items and presents them using customizable layouts.
class UICollectionViewController
A view controller that specializes in managing a collection view.
Data
Updating collection views using diffable data sources
Streamline the display and update of data in a collection view using a diffable data source that contains identifiers.
Implementing modern collection views
Bring compositional layouts to your app and simplify updating your user interface with diffable data sources.
Building high-performance lists and collection views
Improve the performance of lists and collections in your app with prefetching and image preparation.
class UICollectionViewDiffableDataSource
The object you use to manage data and provide cells for a collection view.
protocol UICollectionViewDataSource
The methods adopted by the object you use to manage data and provide cells for a collection view.
protocol UICollectionViewDataSourcePrefetching
A protocol that provides advance warning of the data requirements for a collection view, allowing the triggering of asynchronous data load operations.
struct NSDiffableDataSourceSnapshot
A representation of the state of the data in a view at a specific point in time.
struct NSDiffableDataSourceSectionSnapshot
A representation of the state of the data in a layout section at a specific point in time.
class UIRefreshControl
A standard control that can initiate the refreshing of a scroll view’s contents.
Cells
class UICollectionViewCell
A single data item when that item is within the collection view’s visible bounds.
class UICollectionViewListCell
A collection view cell that provides list features and default styling.
class UICollectionReusableView
A view that defines the behavior for all cells and supplementary views presented by a collection view.
Layouts
Arrange your collection view content in a highly configurable layout.
Selection management
Changing the appearance of selected and highlighted cells
Provide visual feed
Accelerate user selection of multiple items using the multiselect gesture on table and collection views.
Drag and drop
Supporting Drag and Drop in Collection Views
Initiate drags and handle drops from a collection view.
protocol UICollectionViewDragDelegate
The interface for initiating drags from a collection view.
protocol UICollectionViewDropDelegate
The interface for handling drops in a collection view.
protocol UICollectionViewDropCoordinator
An interface for coordinating your custom drop-related actions with the collection view.
class UICollectionViewDropPlaceholder
A placeholder for an item dropped on a collection view.
class UICollectionViewDropProposal
Your proposed solution for handling a drop in a collection view.
protocol UICollectionViewDropItem
The data associated with an item being dropped into the collection view.
protocol UICollectionViewDropPlaceholderContext
An object that contains information about a placeholder in the collection view.
protocol UIDataSourceTranslating
An advanced interface for managing a data source object.
class UICollectionViewPlaceholder
A placeholder for an item dragged or dropped on a collection view.
See Also
Container views
Autosizing Views for Localization in iOS
Add auto layout constraints to your app to achieve localizable views.
Display data in a single column of customizable rows.
class UIStackView
A streamlined interface for laying out a collection of views in either a column or a row.
class UIScrollView
A view that allows the scrolling and zooming of its contained views.
https://developer.apple.com/documentation/uikit/table-views
Collection
- UIKit
- Views and controls
- Table views
API Collection
Table views
Display data in a single column of customizable rows.
Overview
A table view displays a single column of vertically scrolling content, divided into rows and sections. Each row of a table displays a single piece of information related to your app. Sections let you group related rows together. For example, the Contacts app uses a table to display the names of the user’s contacts.
Table views are a collaboration between many different objects, including:
-
Cells. A cell provides the visual representation for your content. You can use the default cells provided by UIKit or define custom cells to suit the needs of your app.
-
Table view controller. You typically use a
UITableViewControllerobject to manage a table view. You can use other view controllers too, but a table view controller is required for some table-related features to work. -
Your data source object. This object adopts the
UITableViewDataSourceprotocol and provides the data for the table. -
Your delegate object. This object adopts the
UITableViewDelegateprotocol and manages user interactions with the table’s contents.
Topics
Essentials
class UITableView
A view that presents data using rows in a single column.
Data
Filling a table with data
Create and configure cells for your table dynamically using a data source object, or provide them statically from your storyboard.
Asynchronously loading images into table and collection views
Store and fetch images asynchronously to make your app more responsive.
protocol UITableViewDataSource
The methods that an object adopts to manage data and provide cells for a table view.
protocol UITableViewDataSourcePrefetching
A protocol that provides advance warning of the data requirements for a table view, allowing you to start potentially long-running data operations early.
class UITableViewDiffableDataSource
The object you use to manage data and provide cells for a table view.
struct NSDiffableDataSourceSnapshot
A representation of the state of the data in a view at a specific point in time.
class UILocalizedIndexedCollation
An object that organizes, sorts, and localizes the data for a table view that has a section index.
protocol UIDataSourceTranslating
An advanced interface for managing a data source object.
class UIRefreshControl
A standard control that can initiate the refreshing of a scroll view’s contents.
Table management
Estimating the height of a table’s scrolling area
Provide height estimates for your table view’s headers, footers, and rows to ensure that scrolling accurately reflects the size of your content.
class UITableViewController
A view controller that specializes in managing a table view.
protocol UITableViewDelegate
Methods for managing selections, configuring section headers and footers, deleting and reordering cells, and performing other actions in a table view.
class UITableViewFocusUpdateContext
A context object that provides information relevant to a specific focus update from one view to another.
Cells, headers, and footers
Configuring the cells for your table
Specify the appearance and content of your table’s rows by defining one or more prototype cells in your storyboard.
Creating self-sizing table view cells
Create table view cells that support Dynamic Type and use system spacing constraints to adjust the spacing surrounding text labels.
Adding headers and footers to table sections
Differentiate groups of rows visually by adding header and footer views to your table view’s sections.
class UITableViewCell
The visual representation of a single row in a table view.
class UITableViewHeaderFooterView
A reusable view that you place at the top or bottom of a table section to display additional information for that section.
Row actions
class UISwipeActionsConfiguration
The set of actions to perform when swiping on rows of a table.
class UIContextualAction
An action to display when the user swipes a table row.
class UITableViewRowAction
A single action to present when the user swipes horizontally in a table row.
Deprecated
Selection management
Handling row selection in a table view
Detect when a user taps a table view cell so your app can take the next indicated action.
Selecting multiple items with a two-finger pan gesture
Accelerate user selection of multiple items using the multiselect gesture on table and collection views.
Drag and drop
Supporting drag and drop in table views
Initiate drags and handle drops from a table view.
Adopting drag and drop in a table view
Demonstrates how to enable and implement drag and drop for a table view.
protocol UITableViewDragDelegate
The interface for initiating drags from a table view.
protocol UITableViewDropDelegate
The interface for handling drops in a table view.
protocol UITableViewDropCoordinator
An interface for coordinating your custom drop-related actions with the table view.
protocol UITableViewDropItem
The data associated with an item being dropped into the table view.
class UITableViewDropProposal
Your proposed solution for handling a drop in a table view.
Placeholder cells
protocol UITableViewDropPlaceholderContext
An object for tracking a placeholder cell that you added to your table during a drop operation.
class UITableViewDropPlaceholder
A placeholder cell that supports customizing the drop preview parameters.
class UITableViewPlaceholder
An object that contains information about a placeholder cell being inserted into a table.
See Also
Container views
Autosizing Views for Localization in iOS
Add auto layout constraints to your app to achieve localizable views.
Display nested views using a configurable and highly customizable layout.
class UIStackView
A streamlined interface for laying out a collection of views in either a column or a row.
class UIScrollView
A view that allows the scrolling and zooming of its contained views.
https://developer.apple.com/documentation/uikit/uistackview
- UIKit
- UIStackView
Class
UIStackView
A streamlined interface for laying out a collection of views in either a column or a row.
@MainActor class UIStackView
Overview
Stack views let you leverage the power of Auto Layout, creating user interfaces that can dynamically adapt to the device’s orientation, screen size, and any changes in the available space. The stack view manages the layout of all the views in its arrangedSubviews property. These views are arranged along the stack view’s axis, based on their order in the arrangedSubviews array. The exact layout varies depending on the stack view’s axis, distribution, alignment, spacing, and other properties.
To use a stack view, open the Storyboard you wish to edit. Drag either a Horizontal Stack View or a Vertical Stack View out from the Object library, and position the stack view where desired. Next, drag out the stack’s content, dropping the view or control into the stack. You can continue to add views and controls to your stack, as needed. Interface Builder resizes the stack based on its content. You can also adjust the appearance of the stack’s content by modifying the Stack View’s properties in the Attributes inspector.
Stack view and Auto Layout
The stack view uses Auto Layout to position and size its arranged views. The stack view aligns the first and last arranged view with its edges along the stack’s axis. In a horizontal stack, this means the first arranged view’s leading edge is pinned to the stack’s leading edge, and the last arranged view’s trailing edge is pinned to the stack’s trailing edge. In vertical stacks, the top and bottom edges are pinned to the stack’s top and bottom edges, respectively. If you set the stack view’s isLayoutMarginsRelativeArrangement property to true, the stack view pins its content to the relevant margin instead of its edge.
For all distributions except the UIStackView.Distribution.fillEqually distribution, the stack view uses each arranged view’s intrinsicContentSize property when calculating its size along the stack’s axis. UIStackView.Distribution.fillEqually resizes all the arranged views so they’re the same size, filling the stack view along its axis. If possible, the stack view stretches all the arranged views to match the view with the longest intrinsic size along the stack’s axis.
For all alignments except the UIStackView.Alignment.fill alignment, the stack view uses each arranged view’s intrinsicContentSize property when calculating its size perpendicular to the stack’s axis. UIStackView.Alignment.fill resizes all the arranged views so that they fill the stack view perpendicularly to its axis. If possible, the stack view stretches all the arranged views to match the view with the largest intrinsic size perpendicular to the stack’s axis.
Position and size the stack view
Although a stack view allows you to lay out its contents without using Auto Layout directly, you still need to use Auto Layout to position the stack view itself. In general, this means pinning at least two adjacent edges of the stack view to define its position. Without additional constraints, the system calculates the size of the stack view based on its contents.
-
Along the stack view’s axis, its fitting size is equal to the sum of the sizes of all the arranged views plus the space between views.
-
Perpendicular to the stack view’s axis, its fitting size is equal to the size of the largest arranged view.
-
If the stack view’s
isLayoutMarginsRelativeArrangementproperty is set totrue, the stack view’s fitting size is increased to include space for the margins.
You can provide additional constraints to specify the stack view’s height, width, or both. In these cases, the stack view adjusts the layout and size of its arranged views to fill the specified area. The exact layout varies based on the stack view’s properties. See the UIStackView.Distribution and UIStackView.Alignment enumerations for a complete description on how the stack view handles having either extra space or insufficient space for its content.
You can also position a stack view based on its first or last baseline, instead of using the top, bottom, or center Y position. Like the stack view’s fitting size, these baselines are calculated based on the stack view’s content.
-
A horizontal stack view returns its tallest view for both the
forFirstBaselineLayoutandforLastBaselineLayoutmethods. If the tallest view is also a stack view, it returns the result of callingforFirstBaselineLayoutorforLastBaselineLayouton the nested stack view. -
A vertical stack view returns its first arranged view for
forFirstBaselineLayoutand its last arranged view forforLastBaselineLayout. If either of these views are also stack views, then it returns the result of callingforFirstBaselineLayoutorforLastBaselineLayouton the nested stack view.
Define common stack view layouts
Common approaches for laying out content using stack views:
Define the position only. You can define the stack view’s position by pinning two of its adjacent edges to its superview. In this case, the stack view’s size grows freely in both dimensions, based on its arranged views. This approach is particularly useful when you want the stack view’s content to appear at its intrinsic content size, and you want to arrange other user-interface elements relative to the stack view.
The following image shows a stack view with its leading and top edges pinned to its superview. The labels are first baseline aligned, with an 8-point space between them, left-aligning the stack view’s content in its superview.
Define the stack’s size along its axis. In this case, pin both edges of the stack along its axis to its superview, defining the stack view’s size in that dimension. You also need to pin one of the other edges to define the stack view’s position. The stack view sizes and positions its content along its axis to fill the defined space; however, the unpinned edge moves freely, based on the size of the largest arranged view.
The following image shows a stack view with the leading, top, and trailing edges pinned to its superview. Using the fill distribution causes the content to resize to fill the view’s width, and because the text field has a lower content-hugging priority than the label, it’s stretched as necessary.
Define the stack’s size perpendicular to its axis. This approach is similar to the previous example, but you pin the two edges perpendicular to the stack view’s axis and only one edge along the axis. This lets the stack view grow and shrink along its axis as you add and remove arranged views. Unless you use a UIStackView.Distribution.fillEqually distribution, the arranged views are sized according to their intrinsic content size. Perpendicular to the axis, the views are laid out in the defined space based on the stack view’s alignment.
The following image shows a vertical stack containing four labels and a button. The stack uses 8-point spacing and the center alignment. The stack view’s height grows and shrinks as items are added to or removed from the stack.
Define the size and position of the stack view. In this case, you pin all four edges of the stack view, causing the stack view to lay out its content within the provided space.
The following image shows a vertical stack view with all four edges pinned to its superview. By using the center alignment and fill distribution, the stack view ensures that its content is centered horizontally and vertically fills the screen. However, getting the desired layout with this approach requires a couple of additional steps. By default, the stack view vertically stretches the label and not the image view. To resize the image view, lower its content-hugging priority below the label’s content-hugging priority. Additionally, to maintain the image view’s aspect ratio as it resizes, set its Mode to Aspect Fit. Adding an equal width constraint between the image view and the stack view helps ensure the image is sized to fill the available space.
Manage the stack view’s appearance
A stack view manages the position and size of its arranged views. There are a number of properties that define how the stack view lays out its content.
-
The
axisproperty determines the stack’s orientation, either vertically or horizontally. -
The
distributionproperty determines the layout of the arranged views along the stack’s axis. -
The
alignmentproperty determines the layout of the arranged views perpendicular to the stack’s axis. -
The
spacingproperty determines the minimum spacing between arranged views. -
The
isBaselineRelativeArrangementproperty determines whether the vertical spacing between views is measured from the baselines. -
The
isLayoutMarginsRelativeArrangementproperty determines whether the stack view lays out its arranged views relative to its layout margins.
Typically, you use a single stack view to lay out a small number of items. You can build more complex view hierarchies by nesting stack views inside other stack views. For example, the following image shows a vertical stack view containing two horizontal stack views. Each of the horizontal stack views contains a label and a text field.
You can also fine-tune an arranged view’s appearance by adding additional constraints to the arranged view. For example, you can use constraints to set a minimum or maximum height or width for the view. Or you can define an aspect ratio for the view. The stack view uses these constraints when laying out its content.
Maintain consistency between the arranged views and subviews
The stack view ensures that its arrangedSubviews property is always a subset of its subviews property. Specifically, the stack view enforces the following rules:
-
When the stack view adds a view to its
arrangedSubviewsarray, it also adds that view as a subview, if it isn’t already. -
When a subview is removed from the stack view, the stack view also removes it from the
arrangedSubviewsarray. -
Removing a view from the
arrangedSubviewsarray doesn’t remove it as a subview. The stack view no longer manages the view’s size and position, but the view is still part of the view hierarchy, and is rendered on screen if it’s visible.
Although the arrangedSubviews array always contains a subset of the subviews array, the order of these arrays remain independent.
-
The order of the
arrangedSubviewsarray defines the order in which views appear in the stack. For horizontal stacks, the views are laid out in reading order, with the lower index views appearing before the higher index views. In English, for example, the views are laid out in order from left to right. For vertical stacks, the views are laid out from top to bottom, with the lower index views above the higher index views. -
The order of the subviews array defines the Z-order of the subviews. If the views overlap, subviews with a lower index appear behind subviews with a higher index.
Change the stack view’s content dynamically
The stack view automatically updates its layout whenever views are added, removed, or inserted into the arrangedSubviews array, or whenever one of the arranged subviews’s isHidden property changes.
// Appears to remove the first arranged view from the stack. // The view is still inside the stack, it's just no longer visible, and no longer contributes to the layout. let firstView = stackView.arrangedSubviews[0] firstView.isHidden = true
// Appears to remove the first arranged view from the stack. // The view is still inside the stack, it's just no longer visible, and no longer contributes to the layout. UIView * firstView = self.stackView.arrangedSubviews[0]; firstView.hidden = YES;
The stack view also automatically responds to changes to any of its properties. For example, you can dynamically change the stack’s orientation, by updating the stack view’s axis property.
// Toggle between a vertical and horizontal stack. if stackView.axis == .horizontal { stackView.axis = .vertical } else { stackView.axis = .horizontal }
// Toggle between a vertical and horizontal stack. if (self.stackView.axis == UILayoutConstraintAxisHorizontal) { self.stackView.axis = UILayoutConstraintAxisVertical; } else { self.stackView.axis = UILayoutConstraintAxisHorizontal; }
You can animate both changes to the arranged subview’s isHidden property and changes to the stack view’s properties by placing these changes inside an animation block.
// Animates removing the first item in the stack.
let firstView = stackView.arrangedSubviews[0] firstView.isHidden = true }
// Animates removing the first item in the stack.
[UIView animateWithDuration:0.25 animations:^{
UIView * firstView = self.stackView.arrangedSubviews[0];
firstView.hidden = YES;
}];
Finally, you can define size-class specific values for many of the stack view’s properties directly in Interface Builder. The system automatically animates these changes whenever the stack view’s size class changes.
Topics
Initializing a stack view
convenience init(arrangedSubviews: [UIView])
Returns a new stack view object that manages the provided views.
init(frame: CGRect)
Creates a stack view with the specified frame.
init(coder: NSCoder)
Creates a stack view from data in an unarchiver.
Managing arranged subviews
func addArrangedSubview(UIView)
Adds a view to the end of the arranged subviews array.
var arrangedSubviews: [UIView]
The list of views arranged by the stack view.
func insertArrangedSubview(UIView, at: Int)
Adds the provided view to the array of arranged subviews at the specified index.
func removeArrangedSubview(UIView)
Removes the provided view from the stack’s array of arranged subviews.
Configuring the layout
var axis: NSLayoutConstraint.Axis
The axis along which the arranged views lay out.
var alignment: UIStackView.Alignment
The alignment of the arranged subviews perpendicular to the stack view’s axis.
var distribution: UIStackView.Distribution
The distribution of the arranged views along the stack view’s axis.
var spacing: CGFloat
The distance in points between the adjacent edges of the stack view’s arranged views.
var isBaselineRelativeArrangement: Bool
A Boolean value that determines whether the vertical spacing between views is measured from their baselines.
var isLayoutMarginsRelativeArrangement: Bool
A Boolean value that determines whether the stack view lays out its arranged views relative to its layout margins.
Adding space between items
Returns the custom spacing after the specified view.
func setCustomSpacing(CGFloat, after: UIView)
Applies custom spacing after the specified view.
class let spacingUseDefault: CGFloat
The default spacing for subviews within a stack view.
class let spacingUseSystem: CGFloat
The system-defined spacing to the neighboring view.
Constants
enum Distribution
The layout that defines the size and position of the arranged views along the stack view’s axis.
enum Alignment
The layout of arranged views perpendicular to the stack view’s axis.
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
https://developer.apple.com/documentation/uikit/uiscrollview
- UIKit
- UIScrollView
Class
UIScrollView
A view that allows the scrolling and zooming of its contained views.
tvOS
@MainActor class UIScrollView
Overview
UIScrollView is the superclass of several UIKit classes, including UITableView and UITextView.
A scroll view is a view with an origin that’s adjustable over the content view. It clips the content to its frame, which generally (but not necessarily) coincides with that of the app’s main window. A scroll view tracks the movements of fingers, and adjusts the origin accordingly. The view that shows its content through the scroll view draws that portion of itself according to the new origin, which is pinned to an offset in the content view. The scroll view itself does no drawing except for displaying vertical and horizontal scroll indicators. The scroll view must know the size of the content view so it knows when to stop scrolling. By default, it bounces back when scrolling exceeds the bounds of the content.
The object that manages the drawing of content that displays in a scroll view needs to tile the content’s subviews so that no view exceeds the size of the screen. As users scroll in the scroll view, this object adds and removes subviews as necessary.
Because a scroll view has no scroll bars, it must know whether a touch signals an intent to scroll versus an intent to track a subview in the content. To make this determination, it temporarily intercepts a touch-down event by starting a timer and, before the timer fires, seeing if the touching finger makes any movement. If the timer fires without a significant change in position, the scroll view sends tracking events to the touched subview of the content view. If the user then drags their finger far enough before the timer elapses, the scroll view cancels any tracking in the subview and performs the scrolling itself. Subclasses can override the touchesShouldBegin(_:with:in:), isPagingEnabled, and touchesShouldCancel(in:) methods (which the scroll view calls) to affect how the scroll view handles scrolling gestures.
A scroll view also handles zooming and panning of content. As the user makes a pinch-in or pinch-out gesture, the scroll view adjusts the offset and the scale of the content. When the gesture ends, the object managing the content view updates subviews of the content as necessary. (Note that the gesture can end and a finger might still be down.) While the gesture is in progress, the scroll view doesn’t send any tracking calls to the subview.
The UIScrollView class can have a delegate that must adopt the UIScrollViewDelegate protocol. For zooming and panning to work, the delegate must implement both viewForZooming(in:) and scrollViewDidEndZooming(_:with:atScale:). In addition, the maximumZoomScale and minimumZoomScale zoom scales must be different.
State preservation
If you assign a value to this view’s restorationIdentifier property, it attempts to preserve its scrolling-related information between app launches. Specifically, the values of the zoomScale, contentInset, and contentOffset properties are preserved. During restoration, the scroll view restores these values so that the content appears scrolled to the same position as before. For more information about how state preservation and restoration works, see App Programming Guide for iOS.
Topics
Responding to scroll view interactions
var delegate: (any UIScrollViewDelegate)?
The delegate of the scroll view.
protocol UIScrollViewDelegate
The interface for the delegate of a scroll view.
Managing the content size and offset
var contentSize: CGSize
The size of the content view.
var contentOffset: CGPoint
The point at which the origin of the content view is offset from the origin of the scroll view.
func setContentOffset(CGPoint, animated: Bool)
Sets the offset from the content view’s origin that corresponds to the scroll view’s origin.
Managing the content inset behavior
var adjustedContentInset: UIEdgeInsets
The insets derived from the content insets and the safe area of the scroll view.
var contentInset: UIEdgeInsets
The custom distance that the content view is inset from the safe area or scroll view edges.
var contentInsetAdjustmentBehavior: UIScrollView.ContentInsetAdjustmentBehavior
The behavior for determining the adjusted content offsets.
enum ContentInsetAdjustmentBehavior
Constants indicating how safe area insets are added to the adjusted content inset.
func adjustedContentInsetDidChange()
Notifies the scroll view when the adjusted content insets of the scroll view change.
Getting the layout guides
var frameLayoutGuide: UILayoutGuide
The layout guide based on the untransformed frame rectangle of the scroll view.
var contentLayoutGuide: UILayoutGuide
The layout guide based on the untranslated content rectangle of the scroll view.
Configuring the scroll view
var isScrollEnabled: Bool
A Boolean value that determines whether scrolling is enabled.
var isDirectionalLockEnabled: Bool
A Boolean value that determines whether scrolling is disabled in a particular direction.
var isPagingEnabled: Bool
A Boolean value that determines whether paging is enabled for the scroll view.
var scrollsToTop: Bool
A Boolean value that controls whether the scroll-to-top gesture is enabled.
var bounces: Bool
A Boolean value that controls whether the scroll view bounces past the edge of content and back again.
var bouncesHorizontally: Bool
A Boolean value that determines whether the scroll view bounces when it reaches the ends of its horizontal axis.
var bouncesVertically: Bool
A Boolean value that determines whether the scroll view bounces when it reaches the ends of its vertical axis.
var alwaysBounceVertical: Bool
A Boolean value that determines whether bouncing always occurs when vertical scrolling reaches the end of the content.
var alwaysBounceHorizontal: Bool
A Boolean value that determines whether bouncing always occurs when horizontal scrolling reaches the end of the content view.
Managing the scrolling state
var isTracking: Bool
A Boolean value that indicates whether the user has touched the content to initiate scrolling.
var isDragging: Bool
A Boolean value that indicates whether the user has begun scrolling the content.
var isDecelerating: Bool
A Boolean value that indicates whether the content is moving in the scroll view after the user lifted their finger.
var isScrollAnimating: Bool
A Boolean value that indicates whether the scroll view is currently animating a scroll update.
func stopScrollingAndZooming()
Stops active scroll and zoom animations.
var decelerationRate: UIScrollView.DecelerationRate
A floating-point value that determines the rate of deceleration after the user lifts their finger.
struct DecelerationRate
Deceleration rates for the scroll view.
Applying edge effects
var bottomEdgeEffect: UIScrollEdgeEffect
The effect for the bottom edge of the scroll view.
Beta
var leftEdgeEffect: UIScrollEdgeEffect
The effect for the left edge of the scroll view.
var rightEdgeEffect: UIScrollEdgeEffect
The effect for the right edge of the scroll view.
var topEdgeEffect: UIScrollEdgeEffect
The effect for the top edge of the scroll view.
class UIScrollEdgeEffect
Properties of the effect on a particular edge of the scroll view.
class Style
Styles for a scroll view’s edge effect.
Managing the scroll indicator and refresh control
var indicatorStyle: UIScrollView.IndicatorStyle
The style of the scroll indicators.
enum IndicatorStyle
Defines constants that represent the styles of the scroll indicators.
var showsHorizontalScrollIndicator: Bool
A Boolean value that controls whether the horizontal scroll indicator is visible.
var showsVerticalScrollIndicator: Bool
A Boolean value that controls whether the vertical scroll indicator is visible.
var horizontalScrollIndicatorInsets: UIEdgeInsets
The horizontal distance the scroll indicators are inset from the edge of the scroll view.
var verticalScrollIndicatorInsets: UIEdgeInsets
The vertical distance the scroll indicators are inset from the edge of the scroll view.
var automaticallyAdjustsScrollIndicatorInsets: Bool
A Boolean value that indicates whether the system automatically adjusts the scroll indicator insets.
func flashScrollIndicators()
Displays the scroll indicators momentarily.
Displays the scroll indicators during updates to the scroll view’s content offset.
var refreshControl: UIRefreshControl?
The refresh control associated with the scroll view.
class UIRefreshControl
A standard control that can initiate the refreshing of a scroll view’s contents.
Scrolling to a specific location
func scrollRectToVisible(CGRect, animated: Bool)
Scrolls a specific area of the content so that it’s visible in the scroll view.
Managing touches
Overridden by subclasses to customize the default behavior when a finger touches down in displayed content.
Returns whether to cancel touches related to the content subview and start dragging.
var canCancelContentTouches: Bool
A Boolean value that controls whether touches in the content view always lead to tracking.
var delaysContentTouches: Bool
A Boolean value that determines whether the scroll view delays the handling of touch-down gestures.
var directionalPressGestureRecognizer: UIGestureRecognizer
The underlying gesture recognizer for directional button presses.
Zooming and panning
var panGestureRecognizer: UIPanGestureRecognizer
The underlying gesture recognizer for pan gestures.
var pinchGestureRecognizer: UIPinchGestureRecognizer?
The underlying gesture recognizer for pinch gestures.
func zoom(to: CGRect, animated: Bool)
Zooms to a specific area of the content so that it’s visible in the scroll view.
var zoomScale: CGFloat
A floating-point value that specifies the current scale factor applied to the scroll view’s content.
func setZoomScale(CGFloat, animated: Bool)
A floating-point value that specifies the current zoom scale.
var maximumZoomScale: CGFloat
A floating-point value that specifies the maximum scale factor that can apply to the scroll view’s content.
var minimumZoomScale: CGFloat
A floating-point value that specifies the minimum scale factor that can apply to the scroll view’s content.
var isZoomBouncing: Bool
A Boolean value that indicates that zooming has exceeded the scaling limits specified for the scroll view.
var isZooming: Bool
A Boolean value that indicates whether the content view is currently zooming in or out.
var isZoomAnimating: Bool
A Boolean value that indicates whether the scroll view is currently animating a zoom update.
var bouncesZoom: Bool
A Boolean value that determines whether the scroll view animates the content scaling when the scaling exceeds the maximum or minimum limits.
Dismissing the keyboard
var keyboardDismissMode: UIScrollView.KeyboardDismissMode
The manner in which the system dismisses the keyboard when a drag begins in the scroll view.
enum KeyboardDismissMode
Constants that determine how the system dismisses the keyboard when a drag begins in the scroll view.
Managing the index
var indexDisplayMode: UIScrollView.IndexDisplayMode
The manner in which the index appears while the user is scrolling.
enum IndexDisplayMode
Defines constants that represent how the index appears while the user is scrolling.
Controlling content alignment
var contentAlignmentPoint: CGPoint
A point where the scroll view anchors content that’s smaller than the scroll view’s frame.
Nesting scroll views
var transfersHorizontalScrollingToParent: Bool
A Boolean value that determines whether the scroll view passes horizontal scroll events to a superview.
var transfersVerticalScrollingToParent: Bool
A Boolean value that determines whether the scroll view passes vertical scroll events to a superview.
Deprecated
var scrollIndicatorInsets: UIEdgeInsets
The distance the scroll indicators are inset from the edge of the scroll view.
Deprecated
Instance Properties
var allowsKeyboardScrolling: Bool
A Boolean value that determines whether the scroll view allows scrolling its content with hardware keyboard input.
var lookToScrollAxes: UIAxis
Defines which axes are considered for Look to Scroll. Does not affect when isPagingEnabled is true.
Relationships
Inherits From
UIView
Inherited By
UICollectionViewUITableViewUITextView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUIFocusItemScrollableContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Container views
Autosizing Views for Localization in iOS
Add auto layout constraints to your app to achieve localizable views.
Display nested views using a configurable and highly customizable layout.
Display data in a single column of customizable rows.
class UIStackView
A streamlined interface for laying out a collection of views in either a column or a row.
https://developer.apple.com/documentation/uikit/uiactivityindicatorview
- UIKit
- UIActivityIndicatorView
Class
UIActivityIndicatorView
A view that shows that a task is in progress.
tvOS
@MainActor class UIActivityIndicatorView
Overview
You control when an activity indicator animates by calling the startAnimating() and stopAnimating() methods. To automatically hide the activity indicator when animation stops, set the hidesWhenStopped property to true.
You can set the color of the activity indicator by using the color property.
Topics
Creating an activity indicator
init(style: UIActivityIndicatorView.Style)
Creates an activity indicator.
init(frame: CGRect)
Creates an activity indicator with the specified frame rectangle.
init(coder: NSCoder)
Creates an activity indicator from data in an unarchiver.
Managing an activity indicator
func startAnimating()
Starts the animation of the progress indicator.
func stopAnimating()
Stops the animation of the progress indicator.
var isAnimating: Bool
A Boolean value indicating whether the activity indicator is currently running its animation.
var hidesWhenStopped: Bool
A Boolean value that controls whether the activity indicator is hidden when the animation is stopped.
Configuring the activity indicator appearance
var style: UIActivityIndicatorView.Style
The basic appearance of the activity indicator.
var color: UIColor!
The color of the activity indicator.
Constants
enum Style
The visual style of the progress indicator.
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Content views
class UICalendarView
A view that displays a calendar with date-specific decorations, and provides for user selection of a single date or multiple dates.
class UIContentUnavailableView
A view that indicates there’s no content to display.
class UIImageView
A view that displays a single image or a sequence of animated images in your interface.
class UIPickerView
A view that uses a spinning-wheel or slot-machine metaphor to show one or more sets of values.
class UIProgressView
A view that depicts the progress of a task over time.
class UIWebView
A view that embeds web content in your app.
Deprecated
https://developer.apple.com/documentation/uikit/uicalendarview
- UIKit
- UICalendarView
Class
UICalendarView
A view that displays a calendar with date-specific decorations, and provides for user selection of a single date or multiple dates.
@MainActor class UICalendarView
Overview
Use a calendar view to show users specific dates that have additional information (for example, scheduled events) using decorations that you customize. You can also use a calendar view for users to select one specific date, multiple dates, or no date.
To add a calendar view to your interface:
-
Configure the Calendar and Locale for your calendar view to display.
-
Set a date for the calendar view to initially make visible.
-
Create a delegate to provide decorations on specific dates, if desired.
-
Set a selection method and delegate to handle date selection.
-
Set up Auto Layout to position the calendar view in your interface.
You use a calendar view only for the display and selection of dates. If you want to handle date and time selection, use UIDatePicker.
Configure a calendar view
Configure your calendar view to display the type of calendar appropriate to the user’s location and cultural preference, in the user’s preferred language. By default, a calendar view selects the user’s current Calendar and Locale. If users can select a different calendar or locale in your app, configure the calendar view to use those selections.
// Create the calendar view. let calendarView = UICalendarView()
// Create an instance of the Gregorian calendar. let gregorianCalendar = Calendar(identifier: .gregorian)
// Set the calendar displayed by the view. calendarView.calendar = gregorianCalendar
// Set the calendar view's locale. calendarView.locale = Locale(identifier: "zh_TW")
// Set the font design to the rounded system font. calendarView.fontDesign = .rounded
Then, set the calendar view’s initial display to a starting date that’s appropriate for your use case.
// Set the date to display. calendarView.visibleDateComponents = DateComponents( calendar: gregorianCalendar, year: 2024, month: 2, day: 1 )
If you want to restrict the earliest or latest dates a user can view or select in your calendar view, set the availableDateRange.
// Specify the starting date. let fromDateComponents = DateComponents( calendar: gregorianCalendar, year: 2024, month: 1, day: 1 )
// Specify the ending date. let toDateComponents = DateComponents( calendar: gregorianCalendar, year: 2024, month: 12, day: 31 )
// Verify that you have valid start and end dates. guard let fromDate = fromDateComponents.date, let toDate = toDateComponents.date else { // Handle the error here. fatalError("Invalid date components: (fromDateComponents) and (toDateComponents)") }
// Set the range of dates that people can view. let calendarViewDateRange = DateInterval(start: fromDate, end: toDate) calendarView.availableDateRange = calendarViewDateRange
Display decorations for specific dates
Use decorations to show users which specific dates have additional information. Add meaning or emphasis to the decorations by setting the color, size, image, or custom view that you display for a specific date. To display decorations in your calendar view, create a custom UICalendarViewDelegate object, implement calendarView(_:decorationFor:), and set your custom object as the calendar view’s delegate.
// Define a calendar view delegate. class CalendarViewDelegate: NSObject, UICalendarViewDelegate {
var calendarView: UICalendarView? = nil var decorations: [Date?: UICalendarView.Decoration]
override init() { // Create the date components for Valentine's day that // contain the calendar, year, month, and day. let valentinesDay = DateComponents( calendar: Calendar(identifier: .gregorian), year: 2024, month: 2, day: 14 )
// Create a calendar decoration for Valentine's day. let heart = UICalendarView.Decoration.image( UIImage(systemName: "heart.fill"), color: UIColor.red, size: .large )
decorations = [valentinesDay.date: heart] }
// Return a decoration (if any) for the specified day.
// Get a copy of the date components that only contain // the calendar, year, month, and day. let day = DateComponents( calendar: dateComponents.calendar, year: dateComponents.year, month: dateComponents.month, day: dateComponents.day )
// Return any decoration saved for that date. return decorations[day.date] } }
In your implementation, you can decide which type of UICalendarView.Decoration best illustrates your user’s events:
-
The default decoration, which displays a filled circle you can customize with a color and relative size
-
An image decoration, which you can customize with a system symbol or image, color, and relative size
-
A custom decoration, which you can customize with a closure that returns your custom view
When your data changes, tell the calendar view to reload decoration views.
// Add a decoration to the specified date. func add(decoration: UICalendarView.Decoration, on date: Date) { // Get the calendar, year, month, and day date components for // the specified date. let dateComponents = Calendar.current.dateComponents( [.calendar, .year, .month, .day ], from: date )
// Add the decoration to the decorations dictionary. decorations[dateComponents.date] = decoration
// Reload the calendar view's decorations. if let calendarView { calendarView.reloadDecorations( forDateComponents: [dateComponents], animated: true ) } }
Handle date selection
Let users select a single date, multiple dates, or no date with your calendar view. First, decide which type of date selection you want. Then create a selection object and delegate for that type, and assign it to the calendar view’s selectionBehavior.
let dateSelection = UICalendarSelectionSingleDate(delegate: self) calendarView.selectionBehavior = dateSelection
The user can then select a date from the calendar view. You can set a selected date programmatically as the following example shows:
let date = DateComponents( calendar: Calendar(identifier: .gregorian), year: 2024, month: 2, day: 14 )
// Programmatically set the selected date. dateSelection.selectedDate = date
Next, implement the delegate methods for the selection method to customize your date selection handling.
// Control whether a person can select a given date. func dateSelection( _ selection: UICalendarSelectionSingleDate, canSelectDate dateComponents: DateComponents?
// Allow all dates by returning true if the selection parameter contains // a date component instance. Prevent someone from clearing the selection // by returning false if the selection parameter is nil. return dateComponents != nil }
// Respond when someone selects or deselects a date. If they selected // a date, the dateComponent parameter contains the selected date. If they // cleared the selection, the parameter is nil. func dateSelection(_ selection: UICalendarSelectionSingleDate, didSelectDate dateComponents: DateComponents?) { // Update your app. }
Topics
Setting calendar details
var calendar: Calendar
The calendar that the calendar view illustrates.
var locale: Locale
The locale the calendar view uses for calendar conventions.
var timeZone: TimeZone?
The time zone from the date the calendar view displays.
Setting the visible date and range
var visibleDateComponents: DateComponents
The date components that represent the visible date in the calendar view.
func setVisibleDateComponents(DateComponents, animated: Bool)
Sets the date components that represent the date for the calendar view to make visible, with an option to animate the date change.
var availableDateRange: DateInterval
The range of dates that the calendar view displays.
Customizing the calendar display
var fontDesign: UIFontDescriptor.SystemDesign
A font design that the calendar view uses for displaying calendar text.
var delegate: (any UICalendarViewDelegate)?
A delegate object the calendar view calls for decoration views.
protocol UICalendarViewDelegate
An object that a calendar view uses to display decorations for dates.
class Decoration
A view that a calendar view displays for a specific date.
enum DecorationSize
Constants that indicate the relative size of a decoration in a calendar view.
var wantsDateDecorations: Bool
A Boolean value that indicates whether the calendar view displays date decorations.
func reloadDecorations(forDateComponents: [DateComponents], animated: Bool)
Reloads the decorations for the dates you provide, with an option to animate the decoration reload.
Handling date selections
var selectionBehavior: UICalendarSelection?
The current date selection method of the calendar view.
class UICalendarSelectionSingleDate
An object that tracks a date the user selects from a calendar view.
class UICalendarSelectionMultiDate
An object that tracks multiple dates the user selects from a calendar view.
class UICalendarSelectionWeekOfYear
An object that tracks a specific week a person selects from a calendar view.
class UICalendarSelection
A base object that tracks one or more dates a user selects from a calendar view.
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Content views
class UIActivityIndicatorView
A view that shows that a task is in progress.
class UIContentUnavailableView
A view that indicates there’s no content to display.
class UIImageView
A view that displays a single image or a sequence of animated images in your interface.
class UIPickerView
A view that uses a spinning-wheel or slot-machine metaphor to show one or more sets of values.
class UIProgressView
A view that depicts the progress of a task over time.
class UIWebView
A view that embeds web content in your app.
Deprecated
https://developer.apple.com/documentation/uikit/uicontentunavailableview
- UIKit
- UIContentUnavailableView
Class
UIContentUnavailableView
A view that indicates there’s no content to display.
@MainActor class UIContentUnavailableView
Overview
Use a content-unavailable view to indicate that your app can’t display content. For example, content may not be available if a search returns no results or your app is loading data over the network.
In many cases, you won’t need to create a view of this type directly. Set a UIContentUnavailableConfiguration as the view controller’s contentUnavailableConfiguration, and the view controller manages the layout of the content-unavailable view.
Topics
Initializers
init(coder: NSCoder)
Creates a view from data in an unarchiver.
convenience init(configuration: UIContentUnavailableConfiguration)
Creates a new content-unavailable view with the specified configuration.
Instance Properties
var isScrollEnabled: Bool
A Boolean value that determines whether the view content can scroll.
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCopyableCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUIContentViewUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Content views
class UIActivityIndicatorView
A view that shows that a task is in progress.
class UICalendarView
A view that displays a calendar with date-specific decorations, and provides for user selection of a single date or multiple dates.
class UIImageView
A view that displays a single image or a sequence of animated images in your interface.
class UIPickerView
A view that uses a spinning-wheel or slot-machine metaphor to show one or more sets of values.
class UIProgressView
A view that depicts the progress of a task over time.
class UIWebView
A view that embeds web content in your app.
Deprecated
https://developer.apple.com/documentation/uikit/uiimageview
- UIKit
- UIImageView
Class
UIImageView
A view that displays a single image or a sequence of animated images in your interface.
tvOS
@MainActor class UIImageView
Overview
Image views let you efficiently draw any image that can be specified using a UIImage object. For example, you can use the UIImageView class to display the contents of many standard image files, such as JPEG and PNG files. You can configure image views programmatically or in your storyboard file and change the images they display at runtime. For animated images, you can also use the methods of this class to start and stop the animation and specify other animation parameters.
Understand how images are scaled
An image view uses its contentMode property and the configuration of the image itself to determine how to display the image. It’s best to specify images whose dimensions match the dimensions of the image view exactly, but image views can scale your images to fit all or some of the available space. If the size of the image view itself changes, it automatically scales the image as needed.
For an image without cap insets, the presentation of the image is determined solely by the image view’s contentMode property. The UIView.ContentMode.scaleAspectFit and UIView.ContentMode.scaleAspectFill modes scale the image to fit or fill the space while maintaining the image’s original aspect ratio. The UIView.ContentMode.scaleToFill value scales the image without regard to the original aspect ratio, which can cause the image to appear distorted. Other content modes place the image at the appropriate location in the image view’s bounds without scaling it.
For a resizable image with cap insets, those insets affect the final appearance of the image. Specifically, cap insets define which parts of the image may be scaled and in which directions. You can create a resizable image that stretches using the resizableImage(withCapInsets:resizingMode:) method of UIImage. When using an image of this type, you typically set the image view’s content mode to UIView.ContentMode.scaleToFill so that the image stretches in the appropriate places and fills the image view’s bounds.
For tips on how to prepare images, see Debug issues with your image view. For more information on creating resizable images with cap insets, see UIImage.
Determine the final transparency of the image
Images are composited onto the image view’s background and are then composited into the rest of the window. Any transparency in the image allows the image view’s background to show through. Similarly, any further transparency in the background of the image is dependent on the transparency of the image view and the transparency of the UIImage object it displays. When the image view and its image both have transparency, the image view uses alpha blending to combine the two.
-
The image is composited onto the image view’s background.
-
If the image view’s
isOpaqueproperty istrue, the image’s pixels are composited on top of the image view’s background color and thealphaproperty of the image view is ignored. -
If the image view’s
isOpaqueproperty isfalse, the alpha value of each pixel is multiplied by the image view’salphavalue, with the resulting value becoming the actual transparency value for that pixel. If the image doesn’t have an alpha channel, the alpha value of each pixel is assumed to be1.0.
Animate a sequence of images
An image view can store an animated image sequence and play all or part of that sequence. You specify an image sequence as an array of UIImage objects and assign them to the animationImages property. Once assigned, you can use the methods and properties of this class to configure the animation timing and to start and stop the animation.
Consider the following tips when displaying a sequence of animated images:
-
All images in the sequence should have the same size. When scaling is required, the image view scales each image in the sequence separately. If the images are different sizes, scaling may not yield the results you want.
-
All images in the sequence should use the same content scale factor. Make sure the
scaleproperty of each image contains the same value.
Respond to touch events
Image views ignore user events by default. Normally, you use image views only to present visual content in your interface. If you want an image view to handle user interactions as well, change the value of its isUserInteractionEnabled property to true. After doing that, you can attach gesture recognizers or use any other event handling techniques to respond to touch events or other user-initiated events.
For more information about handling events, see Event Handling Guide for UIKit Apps.
Improve performance
Image scaling and alpha blending are two relatively expensive operations that can impact your app’s performance. To maximize performance of your image view code, consider the following tips:
-
Cache scaled versions of frequently used images. If you expect certain large images to be displayed frequently in a scaled-down thumbnail view, consider creating the scaled-down images in advance and storing them in a thumbnail cache. Doing so alleviates the need for each image view to scale them separately.
-
Use images whose size is close to the size of the image view. Rather than assigning a large image to an image view, created a scaled version that matches the current size of the image view. You can also create a resizable image object using the
UIImage.ResizingMode.tileoption, which tiles the image instead of scaling it. -
Make your image view opaque whenever possible. Unless you’re intentionally working with images that contain transparency (drawing UI elements, for example), make sure the
isOpaqueproperty of your image view is set totrue. For more information about how transparency is determined, see Determine the final transparency of the image.
Debug issues with your image view
If your image view isn’t displaying what you expected, use the following tips to help diagnose the problem:
-
Load images using the correct method. Use the
init(named:in:compatibleWith:)method ofUIImageto load images from asset catalogs or your app’s bundle. For images outside of your app’s bundle, use theimageWithContentsOfFile:method. -
Don’t use image views for custom drawing. The
UIImageViewclass doesn’t draw its content using thedraw(_:)method. Use image views only to present images. To do custom drawing involving images, subclassUIViewdirectly and draw your image there.
Interface Builder attributes
The following table lists the attributes that you configure for image views in Interface Builder.
| Attribute | Discussion |
|---|---|
| Image | The image to display. You can specify any image in your Xcode project, including standalone images and those in image assets. To set this attribute programmatically, use the image or animationImages property. |
| Highlighted | The image to display when the image view is highlighted. To set this attribute programmatically, use the highlightedImage or highlightedAnimationImages property. |
| State | The initial state of the image. Use this attribute to mark the image as highlighted. To set this attribute programmatically, use the isHighlighted property. |
Internationalization
Internationalization of image views is automatic if your view displays only static images loaded from your app bundle. If you’re loading images programmatically, you’re at least partially responsible for loading the correct image.
-
For resources in your app bundle, you do this by specifying the name in the attributes inspector or by calling the
init(named:)class method onUIImageto obtain the localized version of each image. -
For images that aren’t in your app bundle, your code must do the following:
-
Determine which image to load in a manner specific to your app, such as providing a localized string that contains the URL.
-
Load that image by passing the URL or data for the correct image to an appropriate
UIImageclass method, such asimageWithData:orimageWithContentsOfFile:.
For more information, see Localization.
Accessibility
Image views are accessible by default. The default accessibility traits for an image view are Image and User Interaction Enabled.
For more information about making iOS controls accessible, see the accessibility information in UIControl. For general information about making your interface accessible, see Accessibility for UIKit.
State preservation
When you assign a value to an image view’s restorationIdentifier property, it attempts to preserve the frame of the displayed image. Specifically, the class preserves the values of the bounds, center, and transform properties of the view and the anchorPoint property of the underlying layer. During restoration, the image view restores these values so that the image appears exactly as before. For more information about how state preservation and restoration works, see Restoring your app’s state.
Topics
Creating an image view
init(image: UIImage?)
Returns an image view initialized with the specified image.
init(image: UIImage?, highlightedImage: UIImage?)
Returns an image view initialized with the specified regular and highlighted images.
Accessing the displayed images
var image: UIImage?
The image displayed in the image view.
var highlightedImage: UIImage?
The highlighted image displayed in the image view.
Animating a sequence of images
var animationImages: [UIImage]?
An array of UIImage objects to use for an animation.
var highlightedAnimationImages: [UIImage]?
An array of UIImage objects to use for an animation when the view is highlighted.
var animationDuration: TimeInterval
The amount of time it takes to go through one cycle of the images.
var animationRepeatCount: Int
Specifies the number of times to repeat the animation.
func startAnimating()
Starts animating the images in the receiver.
func stopAnimating()
Stops animating the images in the receiver.
var isAnimating: Bool
Returns a Boolean value indicating whether the animation is running.
Configuring the image view
var isUserInteractionEnabled: Bool
A Boolean value that determines whether user events are ignored and removed from the event queue.
var isHighlighted: Bool
A Boolean value that determines whether the image is highlighted.
var tintColor: UIColor!
A color used to tint template images in the view hierarchy.
Configuring the appearance of symbol images
Configuring and displaying symbol images in your UI
Create scalable images that integrate with your app’s text, and adjust the appearance of those images dynamically.
var preferredSymbolConfiguration: UIImage.SymbolConfiguration?
The configuration values to use when rendering the image.
Configuring symbol effects
func addSymbolEffect(some IndefiniteSymbolEffect & SymbolEffect, options: SymbolEffectOptions, animated: Bool, completion: UISymbolEffectCompletion?)
Adds a discrete symbol effect to the image view with the specified options and animation.
func addSymbolEffect(some DiscreteSymbolEffect & IndefiniteSymbolEffect & SymbolEffect, options: SymbolEffectOptions, animated: Bool, completion: UISymbolEffectCompletion?)
Adds a discrete, indefinite symbol effect to the image view with the specified options and animation.
func addSymbolEffect(some DiscreteSymbolEffect & SymbolEffect, options: SymbolEffectOptions, animated: Bool, completion: UISymbolEffectCompletion?)
Adds an indefinite symbol effect to the image view with the specified options and animation.
func setSymbolImage(UIImage, contentTransition: some ContentTransitionSymbolEffect & SymbolEffect, options: SymbolEffectOptions, completion: UISymbolEffectCompletion?)
Sets a symbol image using the specified content-transition effect, options, and completion handler.
func removeSymbolEffect(ofType: some IndefiniteSymbolEffect & SymbolEffect, options: SymbolEffectOptions, animated: Bool, completion: UISymbolEffectCompletion?)
Removes the symbol effect that matches the specified indefinite effect type, using the specified options and animation setting.
func removeSymbolEffect(ofType: some DiscreteSymbolEffect & IndefiniteSymbolEffect & SymbolEffect, options: SymbolEffectOptions, animated: Bool, completion: UISymbolEffectCompletion?)
Removes the symbol effect that matches the specified discrete, indefinite effect type, using the specified options and animation setting.
func removeSymbolEffect(ofType: some DiscreteSymbolEffect & SymbolEffect, options: SymbolEffectOptions, animated: Bool, completion: UISymbolEffectCompletion?)
Removes the symbol effect that matches the specified discrete effect type, using the specified options and animation setting.
func removeAllSymbolEffects(options: SymbolEffectOptions, animated: Bool)
Removes all symbol effects from the image view, using the specified options and animation setting.
typealias UISymbolEffectCompletion
A completion handler for adding and removing symbol effects and transitions.
struct UISymbolEffectCompletionContext
Information about a symbol effect’s addition or removal.
Transitioning between symbol effects
class UISymbolContentTransition
Represents a symbol content transition and options.
Beta
Managing focus-related behaviors
var adjustsImageWhenAncestorFocused: Bool
Allows UIImageView to respond when an ancestor becomes focused.
var focusedFrameGuide: UILayoutGuide
The layout guide to use when the image view is focused.
var masksFocusEffectToContents: Bool
A Boolean value indicating whether the floating focused appearance uses the image’s alpha channel.
Layering content on top of the image view
var overlayContentView: UIView
A view for hosting layered content on top of the image view.
Specifying the dynamic range
var imageDynamicRange: UIImage.DynamicRange
var preferredImageDynamicRange: UIImage.DynamicRange
enum DynamicRange
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCopyableCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityContentSizeCategoryImageAdjustingUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Content views
class UIActivityIndicatorView
A view that shows that a task is in progress.
class UICalendarView
A view that displays a calendar with date-specific decorations, and provides for user selection of a single date or multiple dates.
class UIContentUnavailableView
A view that indicates there’s no content to display.
class UIPickerView
A view that uses a spinning-wheel or slot-machine metaphor to show one or more sets of values.
class UIProgressView
A view that depicts the progress of a task over time.
class UIWebView
A view that embeds web content in your app.
Deprecated
https://developer.apple.com/documentation/uikit/uipickerview
https://developer.apple.com/documentation/uikit/uiprogressview
- UIKit
- UIProgressView
Class
UIProgressView
A view that depicts the progress of a task over time.
tvOS
@MainActor class UIProgressView
Overview
The UIProgressView class provides properties for managing the style of the progress bar and for getting and setting values that are pinned to the progress of a task.
For an indeterminate progress indicator — or a “spinner” — use an instance of the UIActivityIndicatorView class.
Topics
Creating a progress view
convenience init(progressViewStyle: UIProgressView.Style)
Creates a progress view with the specified style.
init(frame: CGRect)
Creates a progress view with the specified frame rectangle.
init?(coder: NSCoder)
Creates a progress view from data in an unarchiver.
Managing the progress bar
var progress: Float
The current progress of the progress view.
func setProgress(Float, animated: Bool)
Adjusts the current progress of the progress view, optionally animating the change.
var observedProgress: Progress?
The progress object to use for updating the progress view.
Configuring the progress bar
var progressViewStyle: UIProgressView.Style
The current graphical style of the progress view.
var progressTintColor: UIColor?
The color shown for the portion of the progress bar that’s filled.
var progressImage: UIImage?
An image to use for the portion of the progress bar that’s filled.
var trackTintColor: UIColor?
The color shown for the portion of the progress bar that isn’t filled.
var trackImage: UIImage?
An image to use for the portion of the track that isn’t filled.
Constants
enum Style
The styles permitted for the progress bar.
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Content views
class UIActivityIndicatorView
A view that shows that a task is in progress.
class UICalendarView
A view that displays a calendar with date-specific decorations, and provides for user selection of a single date or multiple dates.
class UIContentUnavailableView
A view that indicates there’s no content to display.
class UIImageView
A view that displays a single image or a sequence of animated images in your interface.
class UIPickerView
A view that uses a spinning-wheel or slot-machine metaphor to show one or more sets of values.
class UIWebView
A view that embeds web content in your app.
Deprecated
https://developer.apple.com/documentation/uikit/uiwebview
https://developer.apple.com/documentation/uikit/responding-to-control-based-events-using-target-action
- UIKit
- Views and controls
- Responding to control-based events using target-action
Article
Responding to control-based events using target-action
Handle user input by connecting buttons, sliders, and other controls to your app’s code using the target-action design pattern.
Overview
User interactions generate thousands of events for your app. Every swipe of the finger or button click, for instance, results in numerous events your app has to process.
Target-action is a design pattern to help you handle these user interactions efficiently. By only registering actions against specific events on your controls, you simplify your event processing, while making your code more maintainable and easier to read.
Use target-action to connect events directly from controls in your UI to methods in your code.
Designate an object to handle control-related events
When a person interacts with your control, the control needs to know where to send the event. The destination for the event is the target. View controllers make good targets because they’re adept at handling user interactions, as well as hosting UI controls.
Define the action methods you use to respond to events
With a control assigned to the target, provide a function to call on that target when the event occurs. This is the action method.
Action methods have a distinct signature:
// UIKit. @IBAction func doSomething() @IBAction func doSomething(sender: Any) @IBAction func doSomething(sender: Any, forEvent event: UIEvent)
// AppKit. @IBAction func doSomething() @IBAction func doSomething(sender: Any)
// UIKit.
- (IBAction)doSomething;
- (IBAction)doSomething:(id)sender;
- (IBAction)doSomething:(id)sender forControlEvents:(UIControlEvents)controlEvents;
// AppKit.
- (IBAction)doSomething;
- (IBAction)doSomething:(id)sender;
Xcode uses the @IBAction keyword to connect controls in Interface Builder to functions in your code. The keyword also bridges the Swift and Objective-C runtimes, enabling Swift code to call into Objective-C, which is where the target-action functionality lives.
The sender parameter defines where the event comes from; for example, a button. Use the generic type Any to allow any control to call the action method, or specify the sender type when you need more information about the control for event processing. For example, set the sender type to UISlider to read the slider thumb value when someone moves the slider left or right.
// UIKit. @IBAction func adjustVolume(sender: UISlider) { print(sender.value) }
// AppKit. @IBAction func adjustVolume(sender: NSSlider) { NSLog("%@", sender.stringValue) }
// UIKit.
- (IBAction)adjustVolume:(UISlider *)sender { NSLog(@"%f", sender.value); }
// AppKit.
- (IBAction)adjustVolume:(NSSlider *)sender { NSLog(@"%@", [sender stringValue]); }
UIKit also supports coupling action methods to specific event types (see UIControl.Event). For example, to set up target-action for a user dragging their finger inside the bounds of a control, register for the event type touchDragInside.
Connect controls to the action methods in Interface Builder
With the target and action methods defined, you’re ready to connect them visually to the controls in Interface Builder.
-
Select the control (the
target) you want to connect to the code (theaction). -
Control-drag the control to the view controller in the document outline.
-
Select the action method that the control connects to.
You can verify that the control and action are connected by moving the pointer over the circular dot to the left of the action method. When you do, Xcode highlights the control.
Another way to connect is to Control-drag the control from Interface Builder into the view controller.
Enter the name of the action method you’d like the control to call and then click Connect.
The following table lists the parameters available for configuration.
| Parameter | Description |
|---|---|
| Connection | The type of connection to make. Select Action to establish a target-action relationship between the control and the target. |
| Object | The target or object your control is connecting to. |
| Name | The name of the function, or action, your control calls when the event occurs. |
| Type | The type of the control sending the event. Choose Any if you don’t require any further information regarding the control’s state. Specify the control type if you require more information from the control for event processing. |
| Event | The UIEvent associated with the action. This feature is only available in UIKit. |
| Arguments | The arguments to include in the signature or your target-action method. Choose None to include no arguments. Choose Sender to pass in the control type as the sender. Choose Sender and Event to pass in both the control type and the event that caused the action. This feature is available only in UIKit. |
Connecting the target-action this way ensures the method signature and parameters are correct as Xcode generates the action method for you.
Connect a control to your code programmatically
In UIKit, use the addTarget(_:action:for:) method to set up target-action programmatically on a control:
import UIKit
class ViewController: UIViewController { let signInButton = UIButton(type: .system)
override func viewDidLoad() { super.viewDidLoad()
signInButton.translatesAutoresizingMaskIntoConstraints = false signInButton.setTitle("Sign in", for: .normal)
// Target-action. signInButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
view.addSubview(signInButton) signInButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true signInButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true }
@IBAction func buttonTapped(sender: UIButton) { print("Sign in successful 🎉") } }
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad { [super viewDidLoad];
UIButton *signInButton = [UIButton buttonWithType:UIButtonTypeSystem]; [signInButton setTitle:@"Sign in" forState:UIControlStateNormal];
signInButton.translatesAutoresizingMaskIntoConstraints = false;
// Target-action. [signInButton addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:signInButton]; [signInButton.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = true; [signInButton.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = true; }
- (void)buttonTapped:(UIButton *)sender { NSLog(@"Sign in successful 🎉"); } @end
In AppKit, use the control’s target and action properties to set target-action programmatically:
import Cocoa
class ViewController: NSViewController { let signInButton = NSButton()
signInButton.translatesAutoresizingMaskIntoConstraints = false signInButton.title = "Sign in"
// Target-action. signInButton.target = self signInButton.action = #selector(buttonTapped(sender:))
@IBAction func buttonTapped(sender: NSButton) { print("Sign in successful 🎉") } }
#import "ViewController.h"
NSButton *signInButton = [[NSButton alloc] initWithFrame: NSMakeRect(20, 20, 100, 80)]; signInButton.translatesAutoresizingMaskIntoConstraints = NO; signInButton.title = @"Sign in"; signInButton.bezelStyle = NSBezelStyleRounded;
// Target-action. signInButton.target = self; signInButton.action = @selector(buttonTapped:);
[self.view addSubview:signInButton]; [signInButton.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = YES; [signInButton.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = YES; }
- (void)buttonTapped:(NSButton *)sender { NSLog(@"Sign in successful 🎉"); }
@end
Enable other objects to respond to control-related events
When the object hosting the control isn’t the one you want handling the event, invoke the responder chain by passing in nil as the target. This causes the control to search the responder chain for the specified action method and invoke it when found. For more information, see Using responders and the responder chain to handle events.
See Also
Controls
class UIControl
The base class for controls, which are visual elements that convey a specific action or intention in response to user interactions.
class UIButton
A control that executes your custom code in response to user interactions.
class UIColorWell
A control that displays a color picker.
class UIDatePicker
A control for inputting date and time values.
class UIPageControl
A control that displays a horizontal series of dots, each of which corresponds to a page in the app’s document or other data-model entity.
class UISegmentedControl
A horizontal control that consists of multiple segments, each segment functioning as a discrete button.
class UISlider
A control for selecting a single value from a continuous range of values.
class UIStepper
A control for incrementing or decrementing a value.
class UISwitch
A control that offers a binary choice, such as on/off.
https://developer.apple.com/documentation/uikit/uibutton
https://developer.apple.com/documentation/uikit/uicolorwell
https://developer.apple.com/documentation/uikit/uidatepicker
https://developer.apple.com/documentation/uikit/uipagecontrol
https://developer.apple.com/documentation/uikit/uisegmentedcontrol
- UIKit
- UISegmentedControl
Class
UISegmentedControl
A horizontal control that consists of multiple segments, each segment functioning as a discrete button.
tvOS
@MainActor class UISegmentedControl
Mentioned in
Attaching gesture recognizers to UIKit controls
Overview
A segmented control can display a title (an NSString object) or an image ( UIImage object). The UISegmentedControl object automatically resizes segments to fit proportionally within their superview unless they have a specific width set. When you add and remove segments, you can request that the action be animated with sliding and fading effects.
You register the target-action methods for a segmented control using the valueChanged constant as shown below.
segmentedControl.addTarget(self, action: "action:", forControlEvents: .valueChanged)
[segmentedControl addTarget:self
action:@selector(action:)
forControlEvents:UIControlEventValueChanged];
How you configure a segmented control can affect its display behavior:
-
If you set a segmented control to have a momentary style, a segment doesn’t show itself as selected (blue background) when the user touches it. The disclosure button is always momentary and doesn’t affect the actual selection.
-
In versions of iOS prior to 3.0, if a segmented control has only two segments, then it behaves like a switch — tapping the currently-selected segment causes the other segment to be selected. In iOS 3.0 and later, tapping the currently-selected segment doesn’t cause the other segment to be selected.
Customize appearance
You can customize the appearance of segmented controls using the methods listed in Customizing appearance. You can customize the appearance of all segmented controls using the appearance proxy (for example, [UISegmentedControl appearance]), or just of a single control.
When customizing appearance, in general, you should specify a value for the normal state of a property to be used by other states which don’t have a custom value set. Similarly, when a property is dependent on the bar metrics (on the iPhone in landscape orientation, bars have a different height from standard), you should make sure you specify a value for UIBarMetrics.default.
In the case of the segmented control, appearance properties for landscapePhone are only respected for segmented controls in the smaller navigation and toolbars that are used in landscape orientation on the iPhone.
To provide complete customization, you need to provide divider images for different state combinations, using setDividerImage(_:forLeftSegmentState:rightSegmentState:barMetrics:):
// Image between two unselected segments. mySegmentedControl.setDividerImage(myImage, forLeftSegmentState: UIControlState.Normal, rightSegmentState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
// Image between segment selected on the left and unselected on the right. mySegmentedControl.setDividerImage(myImage, forLeftSegmentState: UIControlState.Selected, rightSegmentState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
// Image between segment selected on the right and unselected on the left. mySegmentedControl.setDividerImage(myImage, forLeftSegmentState: UIControlState.Normal, rightSegmentState: UIControlState.Selected, barMetrics: UIBarMetrics.Default)
// Image between two unselected segments.
[mySegmentedControl setDividerImage:image1 forLeftSegmentState:UIControlStateNormal
rightSegmentState:UIControlStateNormal barMetrics:barMetrics];
// Image between segment selected on the left and unselected on the right.
[mySegmentedControl setDividerImage:image1 forLeftSegmentState:UIControlStateSelected
rightSegmentState:UIControlStateNormal barMetrics:barMetrics];
// Image between segment selected on the right and unselected on the right.
[mySegmentedControl setDividerImage:image1 forLeftSegmentState:UIControlStateNormal
rightSegmentState:UIControlStateSelected barMetrics:barMetrics];
Topics
Creating a segmented control
Creates a segmented control with segments having the given titles or images.
convenience init(frame: CGRect, actions: [UIAction])
Creates a segmented control with the given frame and adds segments for the actions you specify.
init(frame: CGRect)
Creates an empty segmented control with the frame you specify.
init?(coder: NSCoder)
Creates a segmented control with data from an unarchiver.
Managing segment content
func setImage(UIImage?, forSegmentAt: Int)
Sets the content of a segment to a given image.
Returns the image for a specific segment.
func setTitle(String?, forSegmentAt: Int)
Sets the title of a segment.
Returns the title of the specified segment.
Managing segment actions
Fetches the action of the segment at the index you specify, if one exists.
func setAction(UIAction, forSegmentAt: Int)
Sets the action for the segment at the index you specify.
Managing segments
var numberOfSegments: Int
Returns the number of segments the segmented control has.
The index of a segment with an action that has an identifier matching the identifier you specify.
func insertSegment(action: UIAction, at: Int, animated: Bool)
Insert a segment with the action you specify at the given index.
func insertSegment(with: UIImage?, at: Int, animated: Bool)
Inserts a segment at the position you specify and gives it an image as content.
func insertSegment(withTitle: String?, at: Int, animated: Bool)
Inserts a segment at the position you specify and gives it a title as content.
func removeAllSegments()
Removes all segments of the segmented control.
func removeSegment(at: Int, animated: Bool)
Removes the segment you specify from the segmented control, optionally animating the transition.
var selectedSegmentIndex: Int
The index number that identifies the selected segment that the user last touched.
class var noSegment: Int
A segment index value indicating that there’s no selected segment.
Managing segment behavior and appearance
var isMomentary: Bool
A Boolean value that determines whether segments in the segmented control show selected state.
func setEnabled(Bool, forSegmentAt: Int)
Enables the segment you specify.
Returns whether the indicated segment is enabled.
func setContentOffset(CGSize, forSegmentAt: Int)
Adjusts the offset for drawing the content (image or text) of the specified segment.
Returns the offset for drawing the content (image or text) of the segment you specify.
func setWidth(CGFloat, forSegmentAt: Int)
Sets the width of the segment at the index you specify.
Returns the width of the segment at the index you specify.
var apportionsSegmentWidthsByContent: Bool
Indicates whether the control attempts to adjust segment widths based on their content widths.
Customizing appearance
var selectedSegmentTintColor: UIColor?
The color to use for highlighting the currently selected segment.
Returns the background image for a given state and bar metrics.
func setBackgroundImage(UIImage?, for: UIControl.State, barMetrics: UIBarMetrics)
Sets the background image for given state and bar metrics.
Returns the positioning offset for a given segment and bar metrics.
func setContentPositionAdjustment(UIOffset, forSegmentType: UISegmentedControl.Segment, barMetrics: UIBarMetrics)
Sets the content positioning offset for a given segment and bar metrics.
enum Segment
Constants for specifying a segment in a control.
Returns the divider image used for a given combination of left and right segment states and bar metrics.
func setDividerImage(UIImage?, forLeftSegmentState: UIControl.State, rightSegmentState: UIControl.State, barMetrics: UIBarMetrics)
Sets the divider image to use for a given combination of left and right segment states and bar metrics.
Returns the text attributes of the title for a given control state.
func setTitleTextAttributes([NSAttributedString.Key : Any]?, for: UIControl.State)
Sets the text attributes of the title for a given control state.
Relationships
Inherits From
UIControl
Conforms To
CALayerDelegateCVarArgCopyableCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUIContextMenuInteractionDelegateUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUISpringLoadedInteractionSupportingUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Controls
Responding to control-based events using target-action
Handle user input by connecting buttons, sliders, and other controls to your app’s code using the target-action design pattern.
class UIControl
The base class for controls, which are visual elements that convey a specific action or intention in response to user interactions.
class UIButton
A control that executes your custom code in response to user interactions.
class UIColorWell
A control that displays a color picker.
class UIDatePicker
A control for inputting date and time values.
class UIPageControl
A control that displays a horizontal series of dots, each of which corresponds to a page in the app’s document or other data-model entity.
class UISlider
A control for selecting a single value from a continuous range of values.
class UIStepper
A control for incrementing or decrementing a value.
class UISwitch
A control that offers a binary choice, such as on/off.
https://developer.apple.com/documentation/uikit/uislider
- UIKit
- UISlider
Class
UISlider
A control for selecting a single value from a continuous range of values.
@MainActor class UISlider
Mentioned in
Choosing a user interface idiom for your Mac app
Attaching gesture recognizers to UIKit controls
Responding to control-based events using target-action
Overview
As you move the thumb of a slider, it passes its updated value to any actions attached to it. The appearance of sliders is configurable; you can tint the track and the thumb, and provide images to appear at the ends of the slider. You can add sliders to your interface programmatically or by using Interface Builder.
The following image shows the terms used to describe the constituent parts of a UISlider object in a left-to-right configuration.
To add a slider to your interface:
-
Specify the range of values the slider represents.
-
Optionally, configure the appearance of the slider with appropriate tint colors, and limit images.
-
Connect one or more action methods to the slider.
-
Set up Auto Layout rules to govern the size and position of the slider in your interface.
Respond to user interaction
Sliders use the target-action design pattern to notify your app when the user moves the slider. To be notified when the slider’s value changes, register your action method with the valueChanged event. At runtime, the slider calls your method in response to the user changing the slider’s value.
By default, the slider sends value-changed events continuously as the user moves the slider’s thumb control. Setting the isContinuous property to false causes the slider to send an event only when the user releases the slider’s thumb control, setting the final value.
You connect a slider to your action method by using the addTarget(_:action:for:) method or by creating a connection in Interface Builder. The signature of an action method takes one of three forms, as shown in the following code. Choose the form that provides the information that you need to respond to the value change in the slider.
@IBAction func doSomething() @IBAction func doSomething(sender: UISlider) @IBAction func doSomething(sender: UISlider, forEvent event: UIEvent)
- (IBAction)doSomething;
- (IBAction)doSomething:(id)sender;
- (IBAction)doSomething:(id)sender forEvent:(UIEvent*)event;
Debug sliders
When debugging issues with sliders, follow these tips to avoid common pitfalls:
-
Use either a custom tint color or a custom image, but not both. When customizing slider appearance with images or tint, use one option or the other, but not both. Conflicting settings for track and thumb appearance are resolved in favor of the most recently set value. For example, setting a new minimum track image for any state clears any custom tint color you may have provided for minimum track images. Similarly, setting the thumb tint color removes any custom thumb images associated with the slider.
-
The current value must be between the minimum and maximum values. If you try to programmatically set a slider’s current value to be below the minimum or above the maximum, it’s set to the minimum or maximum instead. However, if you set the value beyond the range of the minimum or maximum in Interface Builder, the minimum or minimum values are updated instead.
-
Set custom images for all control states. If you use custom track and thumb images for your slider, remember to set an image for every possible
UIControl.State. Any control state that doesn’t have a corresponding custom image assigned to it displays the standard image instead. If you set one custom image, be sure to set them all.
Configure slider attributes in Interface Builder
The following table lists the core attributes that you configure for sliders in Interface Builder.
| Attribute | Description |
|---|---|
| Value Minimum / Maximum | Specifies the values attached to the endpoints of the slider, the minimum representing the leading end of the slider and the maximum representing the trailing end. Access these values at runtime using the minimumValue and maximumValue properties. |
| Value Current | Represents the initial value of the slider. The value must be between the minimum and maximum values. Access this value at runtime with the value property. |
The following table lists the attributes that control the appearance of a slider.
| Attribute | Description |
|---|---|
| Min Image | Specifies the image displayed at the leading end of the slider. If blank, no image is displayed. Access this value at runtime with the minimumValueImage property. |
| Max Image | Specifies the image displayed at the trailing end of the slider. If blank, no image is displayed. Access this value at runtime with the maximumValueImage property. |
| Min Track Tint | Specifies the tint color of the track to the leading side of the slider’s thumb. The value defaults to the slider’s inherited tint color. Access this value at runtime with the minimumTrackTintColor property. |
| Max Track Tint | Specifies the tint color of the track to the trailing side of the slider’s thumb. Access this value at runtime with the maximumTrackTintColor property. |
| Thumb Tint | Controls the tint color of the slider’s thumb. Access this value at runtime with the thumbTintColor property. |
The following table lists the attributes that configure the events associated with a slider.
| Attribute | Description |
|---|---|
| Events: Continuous Updates | Controls when attached actions are triggered: when checked, action events are called whenever the thumb is moved during user interaction. When not checked, attached actions are triggered only on completion of user interaction. Access this value at runtime with the isContinuous property. |
For information about the sliders’s inherited Interface Builder attributes, see UIControl and UIView.
Customize the slider’s appearance
Use Auto Layout to specify the position and width of a slider. The intrinsic height is determined by the intrinsic heights of the minimum and maximum images, if present. The width of the track automatically adjusts to accommodate the minimum and maximum images.
The most common way to customize the slider’s appearance is to provide custom minimum and maximum value images. These images sit at either end of the slider control and indicate which value that end of the slider represents. Set the values of the minimumValueImage and maximumValueImage properties to appropriate UIImage objects to display images at the ends of the slider. The following image shows a slider configured with minimum and maximum images that imply volume adjustment.
To set custom tint colors for both the track and the thumb of a slider, use the minimumTrackTintColor, maximumTrackTintColor, and thumbTintColor properties, as shown in the following image.
By default, the minimum track tint color defers to the tint color of the slider control.
To completely change the appearance of the slider, you can specify images for the thumb and the track. Provide images for each of the control states (normal, highlighted, and so on) with the setMinimumTrackImage(_:for:), setMaximumTrackImage(_:for:), and setThumbImage(_:for:) methods. Set the capInsets property for the track images to facilitate horizontal stretching. To access the images used in the current control state, use the currentMinimumTrackImage, currentMaximumTrackImage, and currentThumbImage properties, as shown in the following image.
Provide localized strings
Sliders have no special properties related to internationalization. However, if you use a slider with a label, make sure you provide localized strings for the label.
Sliders automatically adjust to the appropriate interface direction, ensuring that the minimum end of the slider is always at the leading end and the maximum end at the trailing end. If you override minimumValueImageRect(forBounds:) or maximumValueImageRect(forBounds:) in a subclass of UISlider, be sure to take the user interface layout direction into account.
For more information, see Internationalization and Localization Guide.
Make sliders accessible
Sliders are accessible by default. The default accessibility traits for a slider are User Interaction Enabled and Adjustable.
"Sound volume: 13 percent. Adjustable. Swipe up or down with one finger to adjust the value."
For more information about making iOS controls accessible, see the accessibility information in UIControl. For general information about making your interface accessible, see Accessibility Programming Guide for iOS.
Topics
Accessing the slider’s value
var value: Float
The slider’s current value.
func setValue(Float, animated: Bool)
Sets the slider’s current value, allowing you to animate the change visually.
Accessing the slider’s value limits
var minimumValue: Float
The minimum value of the slider.
var maximumValue: Float
The maximum value of the slider.
Modifying the slider’s behavior
var isContinuous: Bool
A Boolean value indicating whether changes in the slider’s value generate continuous update events.
var behavioralStyle: UIBehavioralStyle
The style that determines how the slider behaves.
var preferredBehavioralStyle: UIBehavioralStyle
The preferred behavioral style.
enum UIBehavioralStyle
Constants that indicate how a control behaves in apps built with Mac Catalyst.
Changing the slider’s style
var sliderStyle: UISlider.Style Beta
enum Style Beta
Changing the slider’s appearance
var minimumValueImage: UIImage?
The image that represents the slider’s minimum value.
var maximumValueImage: UIImage?
The image representing the slider’s maximum value.
var minimumTrackTintColor: UIColor?
The color used to tint the default minimum track images.
var currentMinimumTrackImage: UIImage?
The minimum track image currently being used to render the slider.
Returns the minimum track image associated with the specified control state.
func setMinimumTrackImage(UIImage?, for: UIControl.State)
Assigns a minimum track image to the specified control states.
var maximumTrackTintColor: UIColor?
The color used to tint the default maximum track images.
var currentMaximumTrackImage: UIImage?
Contains the maximum track image currently being used to render the slider.
Returns the maximum track image associated with the specified control state.
func setMaximumTrackImage(UIImage?, for: UIControl.State)
Assigns a maximum track image to the specified control states.
var thumbTintColor: UIColor?
The color used to tint the default thumb images.
var currentThumbImage: UIImage?
The thumb image currently being used to render the slider.
Returns the thumb image associated with the specified control state.
func setThumbImage(UIImage?, for: UIControl.State)
Assigns a thumb image to the specified control states.
Configuring the track
var trackConfiguration: UISlider.TrackConfiguration?
struct TrackConfiguration
Overrides for subclasses
Returns the drawing rectangle for the maximum value image.
Returns the drawing rectangle for the minimum value image.
Returns the drawing rectangle for the slider’s track.
Returns the drawing rectangle for the slider’s thumb image.
Relationships
Inherits From
UIControl
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUIContextMenuInteractionDelegateUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Controls
Handle user input by connecting buttons, sliders, and other controls to your app’s code using the target-action design pattern.
class UIControl
The base class for controls, which are visual elements that convey a specific action or intention in response to user interactions.
class UIButton
A control that executes your custom code in response to user interactions.
class UIColorWell
A control that displays a color picker.
class UIDatePicker
A control for inputting date and time values.
class UIPageControl
A control that displays a horizontal series of dots, each of which corresponds to a page in the app’s document or other data-model entity.
class UISegmentedControl
A horizontal control that consists of multiple segments, each segment functioning as a discrete button.
class UIStepper
A control for incrementing or decrementing a value.
class UISwitch
A control that offers a binary choice, such as on/off.
https://developer.apple.com/documentation/uikit/uistepper
- UIKit
- UIStepper
Class
UIStepper
A control for incrementing or decrementing a value.
@MainActor class UIStepper
Mentioned in
Choosing a user interface idiom for your Mac app
Attaching gesture recognizers to UIKit controls
Overview
By default, pressing and holding a stepper’s button increments or decrements the stepper’s value repeatedly. The rate of change depends on how long the user continues pressing the control. To turn off this behavior, set the autorepeat property to false.
The maximum value must be greater than or equal to the minimum value. If you set a maximum or minimum value that would break this invariant, both values are set to the new value. For example, if the minimum value is 200 and you set a maximum value of 100, then both the minimum and maximum become 200.
Topics
Configuring the stepper
var isContinuous: Bool
A Boolean value that determines whether to send value changes during user interaction or after user interaction ends.
var autorepeat: Bool
A Boolean value that determines whether to repeatedly change the stepper’s value as the user presses and holds a stepper button.
var wraps: Bool
A Boolean value that determines whether the stepper can wrap its value to the minimum or maximum value when incrementing and decrementing the value.
var minimumValue: Double
The lowest possible numeric value for the stepper.
var maximumValue: Double
The highest possible numeric value for the stepper.
var stepValue: Double
The step, or increment, value for the stepper.
Accessing the stepper’s value
var value: Double
The numeric value of the stepper.
Customizing appearance
Returns the background image associated with the specified control state.
func setBackgroundImage(UIImage?, for: UIControl.State)
Sets the background image for the control when it’s in the specified state.
Returns the image used for the decrement glyph of the control.
func setDecrementImage(UIImage?, for: UIControl.State)
Sets the image to use for the decrement glyph of the control.
Returns the divider image for the given combination of left and right states.
func setDividerImage(UIImage?, forLeftSegmentState: UIControl.State, rightSegmentState: UIControl.State)
Sets the image to use for the given combination of left and right states.
Returns the image used for the increment glyph of the control.
func setIncrementImage(UIImage?, for: UIControl.State)
Sets the image to use for the increment glyph of the control.
Relationships
Inherits From
UIControl
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUIContextMenuInteractionDelegateUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Controls
Responding to control-based events using target-action
Handle user input by connecting buttons, sliders, and other controls to your app’s code using the target-action design pattern.
class UIControl
The base class for controls, which are visual elements that convey a specific action or intention in response to user interactions.
class UIButton
A control that executes your custom code in response to user interactions.
class UIColorWell
A control that displays a color picker.
class UIDatePicker
A control for inputting date and time values.
class UIPageControl
A control that displays a horizontal series of dots, each of which corresponds to a page in the app’s document or other data-model entity.
class UISegmentedControl
A horizontal control that consists of multiple segments, each segment functioning as a discrete button.
class UISlider
A control for selecting a single value from a continuous range of values.
class UISwitch
A control that offers a binary choice, such as on/off.
https://developer.apple.com/documentation/uikit/uiswitch
- UIKit
- UISwitch
Class
UISwitch
A control that offers a binary choice, such as on/off.
@MainActor class UISwitch
Mentioned in
Attaching gesture recognizers to UIKit controls
Displaying a checkbox in your Mac app built with Mac Catalyst
Choosing a user interface idiom for your Mac app
Overview
The UISwitch class declares a property and a method to control its on/off state. When a person manipulates the switch control (“flips” it), it triggers the valueChanged event.
You can customize the appearance of the switch by changing the color used to tint the switch when it’s on or off.
For information about basic view behaviors, see View Programming Guide for iOS.
Topics
Creating a switch
init(frame: CGRect)
Creates a switch control.
init?(coder: NSCoder)
Creates a switch control from data in an unarchiver.
Setting the on/off state
var isOn: Bool
A Boolean value that determines whether the switch is in the on or off position.
func setOn(Bool, animated: Bool)
Sets the state of the switch to the on or off position, optionally animating the transition.
Setting the display style
Present a switch control as a Mac-style checkbox when your app runs in the Mac user interface idiom.
var preferredStyle: UISwitch.Style
The preferred display style for the switch.
var style: UISwitch.Style
The display style for the switch.
enum Style
Styles that determine the appearance of the switch.
var title: String?
The title displayed next to a checkbox-style switch.
Customizing the appearance of the switch
var onTintColor: UIColor?
The color used to tint the appearance of the switch when it’s in the on position.
var thumbTintColor: UIColor?
The color used to tint the appearance of the thumb.
Deprecated
var onImage: UIImage?
The image displayed when the switch is in the on position.
var offImage: UIImage?
The image displayed when the switch is in the off position.
Relationships
Inherits From
UIControl
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUIContextMenuInteractionDelegateUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Controls
Responding to control-based events using target-action
Handle user input by connecting buttons, sliders, and other controls to your app’s code using the target-action design pattern.
class UIControl
The base class for controls, which are visual elements that convey a specific action or intention in response to user interactions.
class UIButton
A control that executes your custom code in response to user interactions.
class UIColorWell
A control that displays a color picker.
class UIDatePicker
A control for inputting date and time values.
class UIPageControl
A control that displays a horizontal series of dots, each of which corresponds to a page in the app’s document or other data-model entity.
class UISegmentedControl
A horizontal control that consists of multiple segments, each segment functioning as a discrete button.
class UISlider
A control for selecting a single value from a continuous range of values.
class UIStepper
A control for incrementing or decrementing a value.
https://developer.apple.com/documentation/uikit/uilabel
https://developer.apple.com/documentation/uikit/uitextfield
- UIKit
- UITextField
Class
UITextField
An object that displays an editable text area in your interface.
tvOS
@MainActor class UITextField
Mentioned in
Adding Writing Tools support to a custom UIKit view
Adding user-focusable elements to a tvOS app
Adopting system selection UI in custom text views
Customizing Writing Tools behavior for UIKit views
Overview
You use text fields to gather text-based input from the user using the onscreen keyboard. The keyboard is configurable for many different types of input such as plain text, emails, numbers, and so on. Text fields use the target-action mechanism and a delegate object to report changes made during the course of editing.
In addition to its basic text-editing behavior, you can add overlay views to a text field to display additional information and provide additional tappable controls. You might add custom overlay views for elements such as a bookmarks button or search icon. Text fields provide a built-in overlay view to clear the current text. The use of custom overlay views is optional.
After adding a text field to your interface, you configure it for use in your app. Configuration involves performing some or all of the following tasks:
-
Configure one or more targets and actions for the text field.
-
Configure the keyboard-related attributes of the text field.
-
Assign a delegate object to handle important tasks, such as:
-
Determining whether the user should be allowed to edit the text field’s contents.
-
Validating the text entered by the user.
-
Responding to taps in the keyboard’s return button.
-
Forwarding the user-entered text to other parts of your app.
-
Store a reference to the text field in one of your controller objects.
For information about the methods of the text field’s delegate object, see UITextFieldDelegate.
Show and hide the keyboard
When a text field becomes first responder, the system automatically shows the keyboard and binds its input to the text field. A text field becomes the first responder automatically when the user taps it. You can also force a text field to become the first responder by calling its becomeFirstResponder() method. You might force a text field to become first responder when you require the user to enter some information.
You can ask the system to dismiss the keyboard by calling the resignFirstResponder() method of your text field. Usually, you dismiss the keyboard in response to specific interactions. For example, you might dismiss the keyboard when the user taps the keyboard’s return key. The system can also dismiss the keyboard in response to user actions. Specifically, the system dismisses the keyboard when the user taps a new control that doesn’t support keyboard input.
The appearance and dismissal of the keyboard affect the editing state of the text field. When the keyboard appears, the text field enters the editing state and sends the appropriate notifications to its delegate. Similarly, when the text field resigns the first responder status, it leaves the editing state and notifies its delegate. For more information about the sequence of events that occur during editing, see Validate text and manage the editing process.
Configure the keyboard’s appearance
You customize your text field’s keyboard using the properties of the UITextInputTraits protocol, which the UITextField class adopts. UIKit supports standard keyboards for the user’s current language and also supports specialized keyboards for entering numbers, URLs, email addresses, and other specific types of information. You use the properties of this protocol to adjust keyboard traits such as the following:
-
The type of keyboard to display
-
The autocapitalization behavior of the keyboard
-
The autocorrection behavior of the keyboard
-
The type of return key to display
Respond to keyboard-related notifications
Because the system manages the showing and hiding of the keyboard in response to responder changes, it posts the following notifications for tracking the keyboard-related changes:
-
keyboardWillShowNotification -
keyboardDidShowNotification -
keyboardWillHideNotification -
keyboardDidHideNotification -
keyboardWillChangeFrameNotification -
keyboardDidChangeFrameNotification
Each notification contains a userInfo dictionary that includes the size of the keyboard. Because the keyboard can hide portions of your interface, you should use the size information to reposition your content on the screen. For content embedded in a scroll view, you can scroll the text field into view, as illustrated in the following image. In other cases, you can resize your main content view so that it isn’t covered by the keyboard.
For more information about managing keyboard interactions, see Text Programming Guide for iOS.
Format the text in a text field
There are two types of formatting you can do to a text field’s text:
-
You can change the font, color, and style of the text using properties of this class. Alternatively, you can specify an
NSAttributedStringfor the text field’s content. -
You can format the content of a text field using an
Formatterobject.
The font, textColor, and textAlignment properties, among others, affect the appearance of the text field’s string. Modifying these properties applies the specified characteristic to the entire string. To specify more granular formatting, specify the text field’s text using an NSAttributedString object.
The UITextField class doesn’t provide built-in support for formatting its string using an Formatter object, but you can use the text field’s delegate to format the content yourself. To do so, use the text field’s delegate methods to validate text and to format it appropriately. For example, use the textField(_:shouldChangeCharactersIn:replacementString:) method to validate and format text while the user is typing. For information about how to use formatter objects, see Data Formatting Guide.
Use overlay views to edit content
Overlay views are small views displayed on the left and right sides of the text view’s editable area. Typically, overlay views are image-based buttons that you set up as additional editing controls. For example, you might use an overlay view to implement a bookmarks button. To configure a button as an overlay view, specify an image for the button’s content and configure the target and action of the button to respond to taps.
The following code shows how to add a button as the left overlay of a text field. In this case, the code creates a button and configure its size and contents. The leftViewMode property specifies when your button is displayed. When the user taps the button, the button calls the configured action method, which in this case is a custom displayBookmarks: method.
let overlayButton = UIButton(type: .custom) let bookmarkImage = UIImage(systemName: "bookmark") overlayButton.setImage(bookmarkImage, for: .normal) overlayButton.addTarget(self, action: #selector(displayBookmarks), for: .touchUpInside) overlayButton.sizeToFit()
// Assign the overlay button to the text field textField.leftView = overlayButton textField.leftViewMode = .always
UIButton *overlayButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *bookmarkImage = [UIImage systemImageNamed:@"bookmark"];
[overlayButton setImage:bookmarkImage forState:UIControlStateNormal];
[overlayButton addTarget:self action:@selector(displayBookmarks)
forControlEvents:UIControlEventTouchUpInside];
[overlayButton sizeToFit];
// Assign the overlay button to the text field self.textField.leftView = overlayButton; self.textField.leftViewMode = UITextFieldViewModeAlways;
When configuring overlay views, consider whether you want your text field to display the built-in clear button. The clear button provides the user with a convenient way to delete all of the text field’s text. This button is displayed in the right overlay position, but if you provide a custom right overlay view, use the rightViewMode and clearButtonMode properties to define when your custom overlay should be displayed and when the clear button should be displayed.
Validate text and manage the editing process
A text field manages the editing of its text with the help of its delegate object. As the user interacts with a text field, the text field notifies its delegate and gives it a chance to control what is happening. You can use the delegate methods to prevent the user from starting or stopping the editing process or to validate text as it’s typed. You can also use the delegate methods to perform related tasks, such as updating other parts of your interface based on the information typed by the user.
For more information about using the text field’s delegate to manage editing interactions, see UITextFieldDelegate.
Interface Builder attributes
The following table lists the attributes that you configure for text fields in Interface Builder.
| Attribute | Description |
|---|---|
| Text | The initial text displayed by the text field. You can specify the text as a plain string or as an attributed string. If you specify an attributed string, Interface Builder provides different options for editing the font, color, and formatting of the string. |
| Color | The color of the text field’s text. To set this attribute programmatically, use the textColor property. |
| Font | The font of the text field’s text. To set this attribute programmatically, use the font property. |
| Alignment | The alignment of the text field’s text inside the editing area. This option is available only when formatting plain strings. To set this attribute programmatically, use the textAlignment property. |
| Placeholder | The placeholder text displayed by the text field. When the text field’s string is empty, the text field displays this string instead, formatting the string so as to indicate that it isn’t the actual text. Typing any text into the text field hides this string. To set this attribute programmatically, use the placeholder property. |
| Background | The background image to display when the text field is enabled. This image is displayed behind the rest of the text field’s content. To set this attribute programmatically, use the background property. |
| Disabled | The background image to display when the text field is disabled. This image is displayed behind the rest of the text field’s content. To set this attribute programmatically, use the disabledBackground property. |
| Border Style | The visual style for the text field’s border. This attribute defines the visual border, if any, drawn around the editable text region. To set this attribute programmatically, use the borderStyle property. |
| Clear Button | The behavior of the clear button. The clear button is a built-in overlay view that the user taps to delete all of the text in a text field. Use this attribute to define when the clear button appears. To set this attribute programmatically, use the clearButtonMode property. |
| Min Font Size | The minimum font size for the text field’s text. When the Adjust to Fit option is enabled, the text field automatically varies the font size to ensure maximum legibility of the text. You can use this attribute to specify the smallest font size that your consider appropriate for your text. To set this attribute programmatically, use the minimumFontSize property. |
The following table lists the keyboard-related attributes that you configure for text fields. This attributes correspond to properties of the UITextInputTraits protocol that the UITextField class adopts.
For information about additional attributes you can configure for a text view, see UIControl.
Internationalization
The default language of the device affects the keyboard that pops up with the text field (including the return key). You don’t need to do anything to enable this functionality; it’s enabled by default. However, your text field should be able to handle input that comes from any language.
When using storyboards to build your interface, use Xcode’s base internationalization feature to configure the localizations your project supports. When you add a localization, Xcode creates a strings file for that localization. When configuring your interface programmatically, use the system’s built-in support for loading localized strings and resources. For more information about internationalizing your interface, see Localization.
Accessibility
Text fields are accessible by default. The default accessibility trait for a text field is User Interaction Enabled.
For more information about making iOS controls accessible, see the accessibility information in UIControl. For general information about making your interface accessible, see Accessibility for UIKit.
State preservation
When you assign a value to a text field’s restorationIdentifier property, it preserves the selected range of text, if any. During the next launch cycle, the text field attempts to restore that selection. If the selection range can’t be applied to the current text, no selection is made. For more information about how state preservation and restoration works, see App Programming Guide for iOS.
For design guidance, see Human Interface Guidelines.
Topics
Validating and handling edits
var delegate: (any UITextFieldDelegate)?
The text field’s delegate.
protocol UITextFieldDelegate
A set of optional methods to manage editing and validating text in a text field object.
Configuring the text attributes
var text: String?
The text that the text field displays.
var attributedText: NSAttributedString?
The styled text that the text field displays.
var placeholder: String?
The string that displays when there is no other text in the text field.
var attributedPlaceholder: NSAttributedString?
The styled string that displays when there is no other text in the text field.
var defaultTextAttributes: [NSAttributedString.Key : Any]
The default attributes to apply to the text.
var font: UIFont?
The font of the text.
var textColor: UIColor?
The color of the text.
var textAlignment: NSTextAlignment
The technique for aligning the text.
var typingAttributes: [NSAttributedString.Key : Any]?
The attributes to apply to new text that the user enters.
enum BorderStyle
The type of border around the text field.
Sizing the text field’s text
var adjustsFontSizeToFitWidth: Bool
A Boolean value that indicates whether to reduce the font size to fit the text string into the text field’s bounding rectangle.
var minimumFontSize: CGFloat
The size of the smallest permissible font when drawing the text field’s text.
var sizingRule: UILetterformAwareSizingRule
The typographic bounds-sizing behavior that handles text with fonts that contain oversize characters.
Required
Managing the editing behavior
var isEditing: Bool
A Boolean value that indicates whether the text field is currently in edit mode.
var clearsOnBeginEditing: Bool
A Boolean value that determines whether the text field removes old text when editing begins.
var clearsOnInsertion: Bool
A Boolean value that determines whether inserting text replaces the previous contents.
var allowsEditingTextAttributes: Bool
A Boolean value that determines whether the user can edit the attributes of the text in the text field.
enum DidEndEditingReason
Constants that indicate the reason for ending editing in a text field.
class let didEndEditingReasonUserInfoKey: String
A key that indicates the reason for ending editing in a text field.
class let textDidBeginEditingNotification: NSNotification.Name
A notification that alerts observers when an editing session begins in a text field.
class let textDidChangeNotification: NSNotification.Name
A notification that alerts observers when the text in a text field changes.
class let textDidEndEditingNotification: NSNotification.Name
A notification that alerts observers when the editing session ends for a text field.
Setting the view’s background appearance
var borderStyle: UITextField.BorderStyle
The border style for the text field.
var background: UIImage?
The image that represents the background appearance of the text field when it is in an enabled state.
var disabledBackground: UIImage?
The image that represents the background appearance of the text field when it is in a disabled state.
Managing overlay views
var clearButtonMode: UITextField.ViewMode
A mode that controls when the standard Clear button appears in the text field.
var leftView: UIView?
The overlay view that displays on the left (or leading) side of the text field.
var leftViewMode: UITextField.ViewMode
A mode that controls when the left overlay view appears in the text field.
var rightView: UIView?
The overlay view that displays on the right (or trailing) side of the text field.
var rightViewMode: UITextField.ViewMode
A mode that controls when the right overlay view appears in the text field.
enum ViewMode
Constants that define when overlay views appear in a text field.
Drawing and positioning overrides
Returns the drawing rectangle for the text field’s text.
func drawText(in: CGRect)
Draws the text field’s text in the specified rectangle.
Deprecated
Returns the drawing rectangle for the text field’s placeholder text.
func drawPlaceholder(in: CGRect)
Draws the text field’s placeholder text in the specified rectangle.
Returns the text field’s border rectangle.
Returns the rectangle for displaying editable text.
Returns the drawing rectangle for the built-in Clear button.
Returns the drawing rectangle of the text field’s left overlay view.
Returns the drawing location of the text field’s right overlay view.
Replacing the system input views
var inputView: UIView?
The custom input view to display when the text field becomes the first responder.
var inputAccessoryView: UIView?
The custom accessory view to display when the text field becomes the first responder.
Supporting state restoration
var interactionState: Any
Structures
struct TextDidBeginEditingMessage Beta
struct TextDidChangeMessage Beta
struct TextDidEndEditingMessage Beta
Relationships
Inherits From
UIControl
Inherited By
UISearchTextField
Conforms To
CALayerDelegateCVarArgCopyableCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUIContentSizeCategoryAdjustingUIContextMenuInteractionDelegateUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUIKeyInputUILargeContentViewerItemUILetterformAwareAdjustingUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITextDraggableUITextDroppableUITextInputUITextInputTraitsUITextPasteConfigurationSupportingUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Text views
class UILabel
A view that displays one or more lines of informational text.
class UITextView
A scrollable, multiline text region.
Extend the standard drag and drop support for text views to include custom types of content.
https://developer.apple.com/documentation/uikit/uitextview
- UIKit
- UITextView
Class
UITextView
A scrollable, multiline text region.
tvOS
@MainActor class UITextView
Mentioned in
Customizing Writing Tools behavior for UIKit views
Adding Writing Tools support to a custom UIKit view
Making a view into a drop destination
Making a view into a drag source
Adopting system selection UI in custom text views
Overview
UITextView supports the display of text using custom style information and also supports text editing. You typically use a text view to display multiple lines of text, such as when displaying the body of a large text document.
This class supports multiple text styles through use of the attributedText property. (Styled text isn’t supported in versions of iOS earlier than iOS 6.) Setting a value for this property causes the text view to use the style information provided in the attributed string. You can still use the font, textColor, and textAlignment properties to set style attributes, but those properties apply to all of the text in the text view. It’s recommended that you use a text view—and not a UIWebView object—to display both plain and rich text in your app.
Manage the keyboard
When the user taps in an editable text view, that text view becomes the first responder and automatically asks the system to display the associated keyboard. Because the appearance of the keyboard has the potential to obscure portions of your user interface, it’s up to you to make sure that doesn’t happen by repositioning any views that might be obscured. Some system views, like table views, help you by scrolling the first responder into view automatically. If the first responder is at the bottom of the scrolling region, however, you may still need to resize or reposition the scroll view itself to ensure the first responder is visible.
It’s your application’s responsibility to dismiss the keyboard at the time of your choosing. You might dismiss the keyboard in response to a specific user action, such as the user tapping a particular button in your user interface. To dismiss the keyboard, send the resignFirstResponder() message to the text view that’s currently the first responder. Doing so causes the text view object to end the current editing session (with the delegate object’s consent) and hide the keyboard.
The appearance of the keyboard itself can be customized using the properties provided by the UITextInputTraits protocol. Text view objects implement this protocol and support the properties it defines. You can use these properties to specify the type of keyboard (ASCII, Numbers, URL, Email, and others) to display. You can also configure the basic text entry behavior of the keyboard, such as whether it supports automatic capitalization and correction of the text.
Keyboard notifications
When the system shows or hides the keyboard, it posts several keyboard notifications. These notifications contain information about the keyboard, including its size, which you can use for calculations that involve repositioning or resizing views. Registering for these notifications is the only way to get some types of information about the keyboard. The system delivers the following notifications for keyboard-related events:
-
keyboardWillShowNotification -
keyboardDidShowNotification -
keyboardWillHideNotification -
keyboardDidHideNotification
For more information about these notifications, see their descriptions in UIWindow.
State preservation
In iOS 6 and later, if you assign a value to this view’s restorationIdentifier property, it preserves the following information:
-
The selected range of text, as reported by the
selectedRangeproperty. -
The editing state of the text view, as reported by the
isEditableproperty.
During the next launch cycle, the view attempts to restore these properties to their saved values. If the selection range can’t be applied to the text in the restored view, no text is selected. For more information about how state preservation and restoration works, see App Programming Guide for iOS.
For design guidance, see Human Interface Guidelines.
Topics
Initializing the text view
init(frame: CGRect, textContainer: NSTextContainer?)
Creates a new text view with the specified text container.
convenience init(usingTextLayoutManager: Bool)
Creates a new text view, with or without a text layout manager depending on the Boolean value you specify.
init?(coder: NSCoder)
Creates a text view from data in an unarchiver.
Specifying the text content
var text: String!
The text that the text view displays.
var attributedText: NSAttributedString!
The styled text that the text view displays.
Responding to text view changes
var delegate: (any UITextViewDelegate)?
The text view’s delegate.
protocol UITextViewDelegate
The methods for receiving editing-related messages for text view objects.
Configuring appearance attributes
var font: UIFont?
The font of the text.
var textColor: UIColor?
The color of the text.
var textAlignment: NSTextAlignment
The technique for aligning the text.
var typingAttributes: [NSAttributedString.Key : Any]
The attributes to apply to new text that the user enters.
var linkTextAttributes: [NSAttributedString.Key : Any]!
The attributes to apply to links.
var borderStyle: UITextView.BorderStyle
var textHighlightAttributes: [NSAttributedString.Key : Any]!
func drawTextHighlightBackground(for: NSTextRange, origin: CGPoint)
enum BorderStyle
Configuring layout attributes
var textContainerInset: UIEdgeInsets
The inset of the text container’s layout area within the text view’s content area.
var usesStandardTextScaling: Bool
A Boolean value that determines the rendering scale of the text.
var sizingRule: UILetterformAwareSizingRule
The typographic bounds-sizing behavior that handles text with fonts that contain oversize characters.
Required
Formatting special data in text
var dataDetectorTypes: UIDataDetectorTypes
The types of data that convert to tappable URLs in the text view.
struct UIDataDetectorTypes
Constants that define the types of information to detect in text-based content.
Managing the editing behavior
var isEditable: Bool
A Boolean value that indicates whether the text view is editable.
var allowsEditingTextAttributes: Bool
A Boolean value that indicates whether the text view allows the user to edit style information.
class let textDidBeginEditingNotification: NSNotification.Name
A notification that alerts observers when an editing session begins in a text view.
class let textDidChangeNotification: NSNotification.Name
A notification that alerts observers when the text in a text view changes.
class let textDidEndEditingNotification: NSNotification.Name
A notification that alerts observers when the editing session ends for a text view.
Working with the selection
var selectedRange: NSRange
The current selection range of the text view.
func scrollRangeToVisible(NSRange)
Scrolls the text view until the text in the specified range is visible.
var clearsOnInsertion: Bool
A Boolean value that indicates whether inserting text replaces the previous contents.
var isSelectable: Bool
A Boolean value that indicates whether the text view is selectable.
Replacing the system input views
var inputView: UIView?
The custom input view to display when the text view becomes the first responder.
var inputAccessoryView: UIView?
The custom accessory view to display when the text view becomes the first responder.
Supporting Find and Replace
var isFindInteractionEnabled: Bool
A Boolean value that enables a text view’s built-in find interaction.
var findInteraction: UIFindInteraction?
The text view’s built-in find interaction.
Getting the writing tools status
var isWritingToolsActive: Bool
A Boolean value that indicates whether the writing tools are currently interacting with the text view’s content.
Accessing TextKit Objects
var textLayoutManager: NSTextLayoutManager?
The text layout manager that lays out text for the text view’s text container.
var layoutManager: NSLayoutManager
The layout manager that lays out text for the text view’s text container.
var textContainer: NSTextContainer
The text container object that defines the area where text displays in the text view.
var textStorage: NSTextStorage
The text storage object holding the text that displays in the text view.
Supporting state restoration
var interactionState: Any
Structures
struct TextDidBeginEditingMessage Beta
struct TextDidChangeMessage Beta
struct TextDidEndEditingMessage Beta
Instance Properties
var allowedWritingToolsResultOptions: UIWritingToolsResultOptions
var selectedRanges: [NSRange] Beta
var subclassForWritingToolsCoordinator: AnyClass
var textFormattingConfiguration: UITextFormattingViewController.Configuration?
var writingToolsBehavior: UIWritingToolsBehavior
var writingToolsCoordinator: UIWritingToolsCoordinator
Relationships
Inherits From
UIScrollView
Conforms To
CALayerDelegateCVarArgCopyableCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUIContentSizeCategoryAdjustingUICoordinateSpaceUIDynamicItemUIFindInteractionDelegateUIFocusEnvironmentUIFocusItemUIFocusItemContainerUIFocusItemScrollableContainerUIKeyInputUILargeContentViewerItemUILetterformAwareAdjustingUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITextDraggableUITextDroppableUITextInputUITextInputTraitsUITextPasteConfigurationSupportingUITextSearchingUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Text views
class UILabel
A view that displays one or more lines of informational text.
class UITextField
An object that displays an editable text area in your interface.
Extend the standard drag and drop support for text views to include custom types of content.
https://developer.apple.com/documentation/uikit/drag-and-drop-customization
https://developer.apple.com/documentation/uikit/uisearchtextfield
- UIKit
- UISearchTextField
Class
UISearchTextField
A view for displaying and editing text and search tokens.
@MainActor class UISearchTextField
Overview
Use a search text field to display search criteria represented as text and tokens, and allow the user to edit that criteria. Tokens are discrete representations of nontextual content that your app can create and use to represent filters that limit the search results. Tokens always occur contiguously before any text in the search field.
UISearchBar hosts a search text field, but you may also use a search text field in other roles, such as the title view of a UINavigationItem.
Tokens can be programmatically selected by including their position in a range assigned to the selectedTextRange property.
Topics
Converting text into tokens
func replaceTextualPortion(of: UITextRange, with: UISearchToken, at: Int)
Converts text in a search field into a search token.
var textualRange: UITextRange
The range of the field’s text content.
Supporting token interactions
var allowsDeletingTokens: Bool
A Boolean that indicates whether the user can remove tokens from the search field.
var allowsCopyingTokens: Bool
A Boolean that indicates whether the user can copy or drag tokens from the search field.
var delegate: (any UITextFieldDelegate)?
The text field’s delegate.
protocol UISearchTextFieldDelegate
The interface for the delegate of a search field.
protocol UISearchTextFieldPasteItem
A protocol that supports pasting tokens.
Adding and removing tokens
The collection of tokens in the search text field.
func insertToken(UISearchToken, at: Int)
Adds a search token at a specific index.
func removeToken(at: Int)
Removes a particular search token from the search text field.
Customizing token behavior
var tokenBackgroundColor: UIColor!
The background color for all tokens in the search text field.
Returns the search field’s tokens that are within a given range.
Converts a token index into a text position.
Providing search suggestions
var searchSuggestions: [any UISearchSuggestion]?
A list of suggestions to offer as shortcuts below the search field.
Relationships
Inherits From
UITextField
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUIContentSizeCategoryAdjustingUIContextMenuInteractionDelegateUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUIKeyInputUILargeContentViewerItemUILetterformAwareAdjustingUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITextDraggableUITextDroppableUITextInputUITextInputTraitsUITextPasteConfigurationSupportingUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Search field
class UISearchToken
Search criteria in a search text field, represented by text and an optional icon.
https://developer.apple.com/documentation/uikit/uisearchtoken
- UIKit
- UISearchToken
Class
UISearchToken
Search criteria in a search text field, represented by text and an optional icon.
@MainActor class UISearchToken
Overview
Use search tokens to help users understand and edit complex search queries in a UISearchTextField. A token acts like a single character in standard text interactions such as deleting, selecting, or dragging. A search token should always have text and may also have an icon.
Assign a representedObject to each search token that’s meaningful to your app. By attaching this extra data to the token you can reconstruct the full search query using information available in the search field when, for example, your app starts from state restoration or the user starts a search.
See Using suggested searches with a search controller to learn how to use search tokens.
Topics
Creating a search token
init(icon: UIImage?, text: String)
Creates a search token with the specified text and icon (if any).
var representedObject: Any?
The object represented by the search token.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendable
See Also
Search field
class UISearchTextField
A view for displaying and editing text and search tokens.
protocol UISearchTextFieldDelegate
The interface for the delegate of a search field.
https://developer.apple.com/documentation/uikit/uisearchtextfielddelegate
https://developer.apple.com/documentation/uikit/uivisualeffect
- UIKit
- UIVisualEffect
Class
UIVisualEffect
An initializer for visual effect views and blur and vibrancy effect objects.
tvOS
@MainActor class UIVisualEffect
Relationships
Inherits From
NSObject
Inherited By
UIBlurEffectUIGlassContainerEffectUIGlassEffectUIVibrancyEffect
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSCopyingNSObjectProtocolNSSecureCodingSendable
See Also
Visual effects
class UIVisualEffectView
An object that implements some complex visual effects.
class UIVibrancyEffect
An object that amplifies and adjusts the color of the content layered behind a visual effect view.
class UIBlurEffect
An object that applies a blurring effect to the content layered behind a visual effect view.
https://developer.apple.com/documentation/uikit/uivisualeffectview
- UIKit
- UIVisualEffectView
Class
UIVisualEffectView
An object that implements some complex visual effects.
tvOS
@MainActor class UIVisualEffectView
Overview
Depending on the desired effect, the effect may affect content layered behind the view or content added to the visual effect view’s contentView. Apply a visual effect view to an existing view and then apply a UIBlurEffect or UIVibrancyEffect object to apply a blur or vibrancy effect to the existing view. After you add the visual effect view to the view hierarchy, add any subviews to the contentView property of the visual effect view. Don’t add subviews directly to the visual effect view itself.
Set the correct alpha value
When using the UIVisualEffectView class, avoid alpha values that are less than 1. Creating views that are partially transparent causes the system to combine the view and all the associated subviews during an offscreen render pass. UIVisualEffectView objects need to be combined as part of the content they’re layered on top of in order to look correct. Setting the alpha to less than 1 on the visual effect view or any of its superviews causes many effects to look incorrect or not show up at all.
Use masks with a visual effect view
Masks directly applied to a UIVisualEffectView are forwarded to the internal views that provide the visual effect, including the contentView itself. You can also apply masks directly to the contentView. Applying a mask to a superview of a UIVisualEffectView object causes the effect to fail, and an exception is thrown.
Any mask provided to UIVisualEffectView isn’t the view that actually performs the mask. UIKit makes a copy of the view and applies it to each subview. To reflect a size change to the mask, you must apply the change to the original mask and reset it on the effect view.
Capture a snapshot of a visual effect view
Many effects require support from the window that hosts the UIVisualEffectView. Attempting to take a snapshot of only the UIVisualEffectView results in a snapshot that doesn’t contain the effect. To take a snapshot of a view hierarchy that contains a UIVisualEffectView, you must take a snapshot of the entire UIWindow or UIScreen that contains it.
Topics
Creating a visual effect view
init(effect: UIVisualEffect?)
Creates a new visual effect view with the designated visual effect.
init?(coder: NSCoder)
Creates a visual effect view from data in an unarchiver.
Retrieving view information
var contentView: UIView
A view object that can have a visual effect view added to it.
var effect: UIVisualEffect?
The visual effect provided by the view.
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSSecureCodingNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Visual effects
class UIVisualEffect
An initializer for visual effect views and blur and vibrancy effect objects.
class UIVibrancyEffect
An object that amplifies and adjusts the color of the content layered behind a visual effect view.
class UIBlurEffect
An object that applies a blurring effect to the content layered behind a visual effect view.
https://developer.apple.com/documentation/uikit/uivibrancyeffect
- UIKit
- UIVibrancyEffect
Class
UIVibrancyEffect
An object that amplifies and adjusts the color of the content layered behind a visual effect view.
@MainActor class UIVibrancyEffect
Overview
A vibrancy effect is intended to be used as a subview of or layered on top of a UIVisualEffectView that has been configured with a UIBlurEffect. The use of a vibrancy effect can help the content placed inside the contentView become more vivid.
The vibrancy effect is color-dependent. Any subviews that you add to the contentView must implement the tintColorDidChange() method and update themselves accordingly. UIImageView objects with images that have a rendering mode of UIImage.RenderingMode.alwaysTemplate as well as UILabel objects update automatically.
Topics
Creating a vibrancy effect
init(forBlurEffect: UIBlurEffect, style: UIVibrancyEffectStyle)
Creates a vibrancy effect with the specified blur and style values.
init(blurEffect: UIBlurEffect)
Creates a vibrancy effect for a specific blur effect.
enum UIVibrancyEffectStyle
Constants for the vibrancy styles.
Deprecated
Creates a vibrancy effect suitable for use with certain supporting text and template images within a widget.
Deprecated
Creates a vibrancy effect suitable for indicating the secondary importance or relevance of supporting text and template images within a widget.
Creates a vibrancy effect for the specified style.
Creates a vibrancy effect for use in Notification Center.
Relationships
Inherits From
UIVisualEffect
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSCopyingNSObjectProtocolNSSecureCodingSendableSendableMetatype
See Also
Visual effects
class UIVisualEffect
An initializer for visual effect views and blur and vibrancy effect objects.
class UIVisualEffectView
An object that implements some complex visual effects.
class UIBlurEffect
An object that applies a blurring effect to the content layered behind a visual effect view.
https://developer.apple.com/documentation/uikit/uiblureffect
- UIKit
- UIBlurEffect
Class
UIBlurEffect
An object that applies a blurring effect to the content layered behind a visual effect view.
tvOS
@MainActor class UIBlurEffect
Overview
Views that you add to the contentView of a visual effect view aren’t affected by the blur effect.
Topics
Creating a blur effect
init(style: UIBlurEffect.Style)
Creates a blur effect with the designated style.
Constants
enum Style
Blur styles available for blur effect objects.
Relationships
Inherits From
UIVisualEffect
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSCopyingNSObjectProtocolNSSecureCodingSendableSendableMetatype
See Also
Visual effects
class UIVisualEffect
An initializer for visual effect views and blur and vibrancy effect objects.
class UIVisualEffectView
An object that implements some complex visual effects.
class UIVibrancyEffect
An object that amplifies and adjusts the color of the content layered behind a visual effect view.
https://developer.apple.com/documentation/uikit/uibaritem
https://developer.apple.com/documentation/uikit/uibarbuttonitem
- UIKit
- UIBarButtonItem
Class
UIBarButtonItem
A specialized button for placement on a toolbar, navigation bar, or shortcuts bar.
tvOS
@MainActor class UIBarButtonItem
Overview
You typically use Interface Builder to create and configure bar button items. However, you can customize the appearance of buttons by sending the setter messages to UIBarButtonItemAppearance to customize all buttons, or to a specific UIBarButtonItem instance. You can use customized buttons in standard places in a UINavigationItem object or a UIToolbar instance.
In general, specify a value for the normal state so that other states without a custom value set can use it. Similarly, when a property depends on the bar metrics (for instance, on the iPhone in landscape orientation, bars have a different height from the standard), specify a value of UIBarMetrics.default.
Topics
Creating items
convenience init(title: String?, image: UIImage?, primaryAction: UIAction?, menu: UIMenu?)
Creates a plain-style item using the specified title, image, primary action, and context menu.
convenience init(title: String?, image: UIImage?, target: AnyObject?, action: Selector?, menu: UIMenu?)
Creates a plain-style item using the specified title, image, target, action, and context menu.
init()
Initializes the item to its default state.
init?(coder: NSCoder)
Creates an item from data in an unarchiver.
Creating items of a specific style
convenience init(title: String?, style: UIBarButtonItem.Style, target: Any?, action: Selector?)
Creates an item using the specified title, style, target, and action.
convenience init(image: UIImage?, style: UIBarButtonItem.Style, target: Any?, action: Selector?)
Creates an item using the specified image, style, target, and action.
convenience init(image: UIImage?, landscapeImagePhone: UIImage?, style: UIBarButtonItem.Style, target: Any?, action: Selector?)
Creates an item using the specified images, style, target, and action.
Creating system items
convenience init(systemItem: UIBarButtonItem.SystemItem, primaryAction: UIAction?, menu: UIMenu?)
Creates an item using the specified system item, primary action, and context menu.
convenience init(barButtonSystemItem: UIBarButtonItem.SystemItem, target: Any?, action: Selector?)
Creates an item using the specified system item, target, and action.
enum SystemItem
Constants that define system-supplied images for bar button items.
Creating custom items
convenience init(customView: UIView)
Creates an item using the specified custom view.
Creating space items
Creates a new fixed-width space item.
Creates a new fixed space item of zero width.
Beta
Creates a new flexible-width space item.
Creating groups
Places the item in an optional group that a person can move, add to, or remove from the navigation bar during layout customization.
Places the item in a fixed group that a person can’t move or remove from the navigation bar during layout customization.
Places the item in a movable group that a person can move but can’t remove from the navigation bar during layout customization.
Managing the custom view
var customView: UIView?
A custom view representing the item.
Managing the action
var primaryAction: UIAction?
The action associated with the item.
var changesSelectionAsPrimaryAction: Bool
A Boolean value that indicates whether the button represents an action or selection.
var action: Selector?
The selector defining the action message to send to the target object when the user taps this bar button item.
var target: AnyObject?
The object that receives an action when the user selects the item.
Managing the context menu
var menu: UIMenu?
The context menu for this button.
var preferredMenuElementOrder: UIContextMenuConfiguration.ElementOrder
The preferred menu-element ordering strategy for the menu.
Customizing item appearance
var style: UIBarButtonItem.Style
The style of the item.
enum Style
Constants that specify the style of an item.
var tintColor: UIColor?
The tint color to apply to the button item.
var isHidden: Bool
A Boolean that determines the visibility of the item.
var isSelected: Bool
A Boolean value that indicates whether the button is in a selected state.
var width: CGFloat
The width of the item.
The set of possible titles to display on the bar button.
Customizing the Back button
Returns the back button background image for a specified control state and bar metrics.
func setBackButtonBackgroundImage(UIImage?, for: UIControl.State, barMetrics: UIBarMetrics)
Sets the back button background image for a specified control state and bar metrics.
Returns the back button title offset for specified bar metrics.
func setBackButtonTitlePositionAdjustment(UIOffset, for: UIBarMetrics)
Sets the back button title offset for specified bar metrics.
Returns the back button vertical position offset for specified bar metrics.
func setBackButtonBackgroundVerticalPositionAdjustment(CGFloat, for: UIBarMetrics)
Sets the back button vertical position offset for specified bar metrics.
Customizing the background
Returns the background vertical position offset for specified bar metrics.
func setBackgroundVerticalPositionAdjustment(CGFloat, for: UIBarMetrics)
Sets the background vertical position offset for specified bar metrics.
Returns the background image for a specified state and bar metrics.
func setBackgroundImage(UIImage?, for: UIControl.State, barMetrics: UIBarMetrics)
Sets the background image for a specified state and bar metrics.
Returns the background image for the specified state, style, and metrics.
func setBackgroundImage(UIImage?, for: UIControl.State, style: UIBarButtonItem.Style, barMetrics: UIBarMetrics)
Sets the background image for the specified state, style, and metrics.
Customizing the title placement
Returns the title offset for specified bar metrics.
func setTitlePositionAdjustment(UIOffset, for: UIBarMetrics)
Sets the title offset for specified bar metrics.
Configuring symbol effects
var isSymbolAnimationEnabled: Bool
A Boolean value that indicates whether symbol effects animate.
func addSymbolEffect(some IndefiniteSymbolEffect & SymbolEffect, options: SymbolEffectOptions, animated: Bool)
Adds an indefinite symbol effect to the bar button item with the specified options and animation.
func addSymbolEffect(some DiscreteSymbolEffect & IndefiniteSymbolEffect & SymbolEffect, options: SymbolEffectOptions, animated: Bool)
Adds a discrete, indefinite symbol effect to the bar button item with the specified options and animation.
func addSymbolEffect(some DiscreteSymbolEffect & SymbolEffect, options: SymbolEffectOptions, animated: Bool)
Adds a discrete symbol effect to the bar button item with the specified options and animation.
func setSymbolImage(UIImage, contentTransition: some ContentTransitionSymbolEffect & SymbolEffect, options: SymbolEffectOptions)
Sets a symbol image using the specified content-transition effect and options.
func removeSymbolEffect(ofType: some IndefiniteSymbolEffect & SymbolEffect, options: SymbolEffectOptions, animated: Bool)
Removes the symbol effect that matches the specified indefinite effect type, using the specified options and animation setting.
func removeSymbolEffect(ofType: some DiscreteSymbolEffect & IndefiniteSymbolEffect & SymbolEffect, options: SymbolEffectOptions, animated: Bool)
Removes the symbol effect that matches the specified discrete, indefinite effect type, using the specified options and animation setting.
func removeSymbolEffect(ofType: some DiscreteSymbolEffect & SymbolEffect, options: SymbolEffectOptions, animated: Bool)
Removes the symbol effect that matches the specified discrete effect type, using the specified options and animation setting.
func removeAllSymbolEffects(options: SymbolEffectOptions, animated: Bool)
Removes all symbol effects from the bar button item, using the specified options and animation setting.
Getting the group
var buttonGroup: UIBarButtonItemGroup?
The group that the button belongs to.
Representing the item in a menu
var menuRepresentation: UIMenuElement?
A menu element that represents the item when it appears in a menu.
Adding a badge
var badge: UIBarButtonItem.Badge?
struct Badge
Customizing placement in a toolbar
var hidesSharedBackground: Bool
A boolean value indicating whether the background this item may share with other items in the bar should be hidden.
var sharesBackground: Bool
A boolean value indicating whether this bar button item can share a background with other items in a navigation bar or a toolbar.
Relationships
Inherits From
UIBarItem
Conforms To
CVarArgCopyableCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolSendableSendableMetatypeUIAccessibilityIdentificationUIAppearanceUIPopoverPresentationControllerSourceItemUISpringLoadedInteractionSupporting
See Also
Bars
class UIBarItem
An abstract superclass for items that you can add to a bar that appears at the bottom of the screen.
class UIBarButtonItemGroup
A group of one or more bar button items for placement on a navigation bar or shortcuts bar.
class UINavigationBar
Navigational controls that display in a bar along the top of the screen, usually in conjunction with a navigation controller.
class UISearchBar
A specialized view for receiving search-related information from the user.
class UIToolbar
A control that displays one or more buttons along the bottom edge of your interface.
class UITabBar
A control that displays one or more buttons in a tab bar for selecting between different subtasks, views, or modes in an app.
class UITabBarItem
An object that describes an item in a tab bar.
protocol UIBarPositioning
A set of methods for defining the positioning of bars in iOS apps.
protocol UIBarPositioningDelegate
A set of methods that support the positioning of a bar that conforms to the UIBarPositioning protocol.
https://developer.apple.com/documentation/uikit/uibarbuttonitemgroup
https://developer.apple.com/documentation/uikit/uinavigationbar
- UIKit
- UINavigationBar
Class
UINavigationBar
Navigational controls that display in a bar along the top of the screen, usually in conjunction with a navigation controller.
tvOS
@MainActor class UINavigationBar
Mentioned in
Building a desktop-class iPad app
Overview
A UINavigationBar object is a bar, typically displayed at the top of the window, containing buttons for navigating within a hierarchy of screens. The primary components are a left (back) button, a center title, and an optional right button. You can use a navigation bar as a standalone object or in conjunction with a navigation controller object.
A navigation bar is most commonly used within a navigation controller. The UINavigationController object creates, displays, and manages its associated navigation bar, and uses attributes of the view controllers you add to control the content displayed in the navigation bar.
To control a navigation bar when using a navigation controller, the following steps are required:
-
Create a navigation controller in Interface Builder or in the code.
-
Configure the appearance of the navigation bar using the
navigationBarproperty on theUINavigationControllerobject. -
Control the content of the navigation bar by setting the
titleandnavigationItemproperties on eachUIViewControlleryou push onto the navigation controller’s stack.
You can also use a standalone navigation bar, without using a navigation controller. To add a navigation bar to your interface, the following steps are required:
-
Set up Auto Layout rules to govern the position of the navigation bar in your interface.
-
Create a root navigation item to supply the initial title.
-
Configure a delegate object to handle user interactions with the navigation bar.
-
Customize the appearance of the navigation bar.
-
Configure your app to push and pop relevant navigation items as the user navigates through the hierarchical screens.
Use a navigation bar with a navigation controller
If you use a navigation controller to manage the navigation between different screens of content, the navigation controller creates a navigation bar automatically and pushes and pops navigation items when appropriate.
A navigation controller uses the navigationItem property on UIViewController to provide the model objects to its navigation bar when navigating a stack of view controllers. The default navigation item uses the view controller’s title, but you can override the navigationItem on a UIViewController subclass to gain complete control of the navigation bar’s content.
A navigation controller automatically assigns itself as the delegate of its navigation bar object. Therefore, when using a navigation controller, don’t assign a custom delegate object to the corresponding navigation bar.
To access the navigation bar associated with a navigation controller, use the navigationBar property on UINavigationController. See Customize the appearance of a navigation bar for details on how to customize the appearance of a navigation bar.
For information about navigation controllers, see UINavigationController.
Add content to a standalone navigation bar
In the vast majority of scenarios you use a navigation bar as part of a navigation controller. However, there are situations for which you might want to use the navigation bar UI and implement your own approach to content navigation. In these situations, you can use a standalone navigation bar.
When you use a navigation bar as a standalone object, you’re responsible for providing its content. Unlike other types of views, you don’t add subviews to a navigation bar directly. Instead, you use a navigation item (an instance of the UINavigationItem class) to specify what buttons or custom views you want displayed. A navigation item has properties for specifying views on the left, right, and center of the navigation bar and for specifying a custom prompt string.
A navigation bar manages a stack of UINavigationItem objects. Although the stack is there mostly to support navigation controllers, you can use it to implement your own custom navigation interface. The topmost item in the stack represents the navigation item whose contents are currently displayed by the navigation bar. You push new navigation items onto the stack using the pushItem(_:animated:) method and pop items off the stack using the popItem(animated:) method. Both of these changes can be animated for the benefit of the user.
In addition to pushing and popping items, you can also set the contents of the stack directly using either the items property or the setItems(_:animated:) method. You might use this method at launch time to restore your interface to its previous state or to push or pop more than one navigation item at a time. The following figure shows the part of the UINavigationBar API responsible for managing the stack of navigation items.
If you’re using a navigation bar as a standalone object, assign a custom delegate object to the delegate property and use that object to intercept messages coming from the navigation bar. Delegate objects must conform to the UINavigationBarDelegate protocol. The delegate notifications let you track when navigation items are pushed or popped from the stack. You use these notifications to update the rest of your app’s user interface.
For more information about creating navigation items, see UINavigationItem. For more information about implementing a delegate object, see UINavigationBarDelegate.
Customize the appearance of a navigation bar
Navigation bars have two standard appearance styles: white with dark text or black with light text. Use the barStyle property to select the style. Any changes you make to other navigation bar appearance properties override those inferred from the bar style.
Navigation bars are translucent by default; their background color is semitransparent. You can make the navigation bar opaque by setting the isTranslucent property to false.
You can specify a custom tint color for a navigation bar background using the barTintColor property. Setting this property overrides the default color inferred from the bar style. As with all UIView subclasses, you can control the color of the interactive elements within navigation bars, including button images and titles, using the tintColor property.
The titleTextAttributes property specifies the attributes for displaying the bar’s title text. You can specify the font, text color, text shadow color, and text shadow offset for the title in the text attributes dictionary using the font, foregroundColor, and shadow keys in Swift and the NSFontAttributeName, NSForegroundColorAttributeName, and NSShadowAttributeName keys in Objective-C, respectively. For more information about string-formatting attributes, see Character Attributes.
Use the setTitleVerticalPositionAdjustment(_:for:) method to adjust the vertical position of the title. This method allows you to specify the adjustment dependent on the bar height, which is represented by the UIBarMetrics enum. The following figure shows a navigation bar with custom tint color, title text attributes, and bar tint color.
To allow complete customization over the appearance of navigation bars, you can additionally provide custom background and shadow images. To provide a custom background image, use the setBackgroundImage(_:for:barMetrics:) method, providing a UIImage object for the appropriate bar position and metrics values. Use a UIBarPosition value for the bar position argument to specify whether to use the supplied image at the bottom or the top of the window, and if it appears at the top, whether to extend it upward under the status bar. Similarly, you can specify that the image should be used for either compact or default bar metrics, with or without a prompt, by providing a UIBarMetrics value to the bar metrics argument.
To add a shadow, provide a resizable UIImage to the shadowImage property. To use the custom shadow image, you need to have specified a custom background image. The following figure shows a navigation bar with a custom background image, supplied using setBackgroundImage(_:for:barMetrics:) with a bar position value of UIBarPosition.topAttached and a bar metrics value of UIBarMetrics.default. A custom image has also been provided to the shadowImage property.
To see examples of customizing a navigation bar, see Customizing your app’s navigation bar.
Customize a navigation bar with Interface Builder
The following table lists the core attributes that you configure for navigations bars in the Attributes Inspector within Interface Builder.
| Attribute | Description |
|---|---|
| Style | Specifies the UI bar style to apply to the navigation bar. The bar style controls the title color and the bar tint color, but you can override it by providing values for those attributes. Select Translucent to make the navigation bar semitransparent. Access these values at runtime with the barStyle and isTranslucent properties. |
| Bar Tint | Controls the tint color of the navigation bar. This overrides the value implied by the Style attribute. If the Translucent attribute is selected, the Bar Tint color is automatically made semitransparent. Access this value at runtime with the barTintColor property. |
| Shadow Image | Represents the image used as a shadow beneath the navigation bar. This image is stretched horizontally to match the width of the bar. Access this value at runtime with the shadowImage property. |
| Back Image | Specifies the image that appears at the leading edge of the back button. This attribute must be used in combination with the Back Mask attribute. Access this value at runtime with the backIndicatorImage property. |
| Back Mask | Specifies the mask associated with the Back Image attribute. This is used to control the appearance of the Back button during animated transitions, and therefore must be used in conjunction with the Back Image attribute. Access this value at runtime with the backIndicatorTransitionMaskImage property. |
The following table lists the Interface Builder attributes that affect the appearance of the navigation bar’s title.
| Attribute | Description |
|---|---|
| Title Font | The font used to render the title in the center of the navigation bar. Access this value at runtime with the value stored against the font key in Swift or the NSFontAttributeName key in Objective-C in the dictionary in the titleTextAttributes property. |
| Title Color | The color used to render the navigation bar title. Access this value at runtime using the foregroundColor key in Swift or the NSForegroundColorAttributeName key in Objective-C in the dictionary in the titleTextAttributes property. |
| Title Shadow | Specifies the color and offset of the shadow used when rendering the navigation bar’s title. Access these values at runtime with the dictionary in the \ [titleTextAttributes] property, using the shadow key in Swift or the NSShadowAttributeName key in Objective-C. |
Internationalize a navigation bar
To internationalize navigation bars, specify a localized string for each of the displayed string properties of the navigation item model objects.
For more information about internationalizing your interface, see Internationalization and Localization Guide.
Make a navigation bar accessible
Navigation bars are accessible by default. The default accessibility trait for a navigation bar is User Interaction Enabled.
With VoiceOver enabled on an iOS device, after the user navigates to a new view in the hierarchy, VoiceOver reads the navigation bar’s title, followed by the name of the left bar button item. When the user taps an element in a navigation bar, VoiceOver reads the name and the type of the element; for example, “General back button,” “Keyboard heading,” and “Edit button.”
For general information about making your interface accessible, see Accessibility Programming Guide for iOS.
Topics
Responding to navigation bar changes
var delegate: (any UINavigationBarDelegate)?
The navigation bar’s delegate object.
protocol UINavigationBarDelegate
Methods that a navigation bar calls before and after it modifies its stack of navigation items.
Pushing and popping items
func pushItem(UINavigationItem, animated: Bool)
Pushes the given navigation item onto the navigation bar’s stack and updates the UI.
Pops the top item from the navigation bar’s stack and updates the UI.
func setItems([UINavigationItem]?, animated: Bool)
Replaces the navigation items currently managed by the navigation bar with the specified items.
var items: [UINavigationItem]?
An array of navigation items managed by the navigation bar.
var topItem: UINavigationItem?
The navigation item at the top of the navigation bar’s stack.
var backItem: UINavigationItem?
The navigation item that is immediately below the topmost item on a navigation bar’s stack.
Customizing the bar’s appearance
var prefersLargeTitles: Bool
A Boolean value that indicates whether the title displays in a large format.
var standardAppearance: UINavigationBarAppearance
The appearance settings for a standard-height navigation bar.
var compactAppearance: UINavigationBarAppearance?
The appearance settings for a compact-height navigation bar.
var scrollEdgeAppearance: UINavigationBarAppearance?
The appearance settings for the navigation bar when the edge of scrollable content aligns with the edge of the navigation bar.
var compactScrollEdgeAppearance: UINavigationBarAppearance?
The appearance settings for a compact-height navigation bar when the edge of scrollable content aligns with the edge of the navigation bar.
var isTranslucent: Bool
A Boolean value that indicates whether the navigation bar is translucent.
Customize appearance information directly on the navigation bar object.
Building with Mac Catalyst
var behavioralStyle: UIBehavioralStyle
The behavioral style of the navigation bar.
var preferredBehavioralStyle: UIBehavioralStyle
The preferred behavioral style of the navigation bar.
var currentNSToolbarSection: UINavigationBar.NSToolbarSection
The toolbar section that the navigation bar is currently using.
enum NSToolbarSection
Constants that determine how the system hosts the navigation bar in an AppKit toolbar.
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUIBarPositioningUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Container view controllers
Creating a custom container view controller
Create a composite interface by combining content from one or more view controllers with other custom views.
class UISplitViewController
A container view controller that implements a hierarchical interface.
class UINavigationController
A container view controller that defines a stack-based scheme for navigating hierarchical content.
class UINavigationItem
The items that a navigation bar displays when the associated view controller is visible.
class UITabBarController
A container view controller that manages a multiselection interface, where the selection determines which child view controller to display.
class UITabBar
A control that displays one or more buttons in a tab bar for selecting between different subtasks, views, or modes in an app.
class UITabBarItem
An object that describes an item in a tab bar.
class UITab
An object that manages a tab in a tab bar.
class UITabAccessory Beta
class UISearchTab
A tab subclass that represents the system’s search tab.
class UITabGroup
An object that manages a collection of tab objects.
class UIPageViewController
A container view controller that manages navigation between pages of content, where a subview controller manages each page.
https://developer.apple.com/documentation/uikit/uisearchbar
https://developer.apple.com/documentation/uikit/uitoolbar
https://developer.apple.com/documentation/uikit/uitabbar
- UIKit
- UITabBar
Class
UITabBar
A control that displays one or more buttons in a tab bar for selecting between different subtasks, views, or modes in an app.
tvOS
@MainActor class UITabBar
Overview
Typically, you use tab bars in conjunction with a UITabBarController object, but you can also use them as standalone controls in your app. Tab bars always appear across the bottom edge of the screen and display the contents of one or more UITabBarItem objects. A tab bar’s appearance can be customized with a background image or tint color to suit the needs of your interface. Tapping an item selects and highlights that item, and you use the selection of the item to enable the corresponding mode for your app.
You can configure tab bars programmatically or in Interface Builder. A UITabBarController object provides its own tab bar object and you must configure the object provided to you. When creating a tab bar programmatically, use the init(frame:) method or another view initializer method to set its initial configuration. Use the methods of this class to configure the appearance of the tab bar. For tab bars you create yourself, you also use the methods of this class to specify the items displayed by the tab bar.
A tab bar reports selections and user customizations to its delegate object. For tab bars you create yourself, use the delegate to respond to selections or to the addition, removal, or reordering of items in the tab bar. (A UITabBarController object acts as the delegate for the tab bar it manages.) For more information on implementing a tab bar delegate, see UITabBarDelegate.
Configure the tab bar items
You can configure tab bar items using Interface Builder or create and configure them programmatically in your code. Tab bars in Interface Builder come preconfigured with some initial items and you can add, remove, or reorder items as needed. How you configure items at design time depends on whether your tab bar is associated with a UITabBarController object:
-
Configuring your tab bar in Interface Builder:
-
When a
UITabBarControllerobject is present, add or remove view controllers to your scene and create relationship segues between the tab bar controller and each new view controller. Creating a relationship segue automatically adds a new item to the tab bar, and deleting an existing relationship segue removes the corresponding tab bar item. -
When a tab bar controller isn’t present, drag tab bar items from the library onto your tab bar.
-
Configuring your tab bar programmatically:
-
To configure the tab bar associated with a
UITabBarControllerobject, configure the view controllers associated with the tab bar controller. The tab bar automatically obtains its items from thetabBarItemproperty of each view controller associated with the tab bar controller. -
To configure tab bar items directly, use the
setItems(_:animated:)method of the tab bar itself.
A tab bar displays all of its tabs onscreen at once, using the itemPositioning property to determine how to position items in the available space. If you have more items than can fit in the available space, display only a subset of them and let the user select which tabs are displayed. The beginCustomizingItems(_:) method displays an interface for selecting which tab bar items to display.
The contents of each item are stored in a UITabBarItem object. Each item contains a title and an image to display in the tab. You can also use tab bar items to add a badge to the corresponding tab. For more information about creating and configuring items, see UITabBarItem.
Respond to tab selections
For tab bars with an associated tab bar controller, the tab bar controller automatically manages selections and displays the appropriate view controller. The only time you have to manage selections yourself is when you create the tab bar without a tab bar controller. The tab bar reports selections to the tabBar(_:didSelect:) method of its delegate object, which you can use to respond to selection changes. For more information about implementing the delegate object, see UITabBarDelegate.
Configure a tab bar with Interface Builder
The following table lists the attributes that you configure for tab bars in Interface Builder.
| Attribute | Discussion |
|---|---|
| Background | The background image to display for the bar. If you specify a stretchable image, the image is stretched to fit the available space; otherwise, the image is tiled. When you configure a background image, the tab bar ignores the tint color information. To set this attribute programmatically, use the backgroundImage property. |
| Shadow | The custom shadow image for the tab bar. This attribute is ignored if the tab bar does not also have a custom background image. To set this attribute programmatically, use the shadowImage property. |
| Selection | The image to use for the selected tab. To set this attribute programmatically, use the selectionIndicatorImage property. |
| Image Tint | The tint color to apply to the selected item. To set this attribute programmatically, use the tintColor property. |
| Style | The basic style to apply to the bar. You can configure a tab bar with a dark or light style and the bar can be opaque or translucent. To set the style programmatically, use the barStyle and isTranslucent properties. |
| Bar Tint | The tint color to apply to the bar. To set this attribute programmatically, use the barTintColor property. |
| Item Positioning | The positioning scheme to apply to items. Use this attribute to configure how items are spaced across the length of the tab bar. To set this attribute programmatically, use the itemPositioning property. |
Internationalize a tab bar
To internationalize a tab bar, you must provide localized strings for the tab bar item titles.
For more information, see Localization.
Make a tab bar accessible
Tab bars are accessible by default.
With VoiceOver enabled on an iOS device, when a user touches a tab in a tab bar, VoiceOver reads the title of the tab, its position in the bar, and whether it’s selected. For example in the iTunes app on iPad, you might hear “Selected, Audiobooks, four of seven” or “Genius, six of seven.”
For general information about making your interface accessible, see Accessibility for UIKit.
For design guidance, see Human Interface Guidelines.
Topics
Customizing the tab bar behavior
var delegate: (any UITabBarDelegate)?
The tab bar’s delegate object.
protocol UITabBarDelegate
The UITabBarDelegate protocol defines optional methods for a delegate of a UITabBar object. The UITabBar class provides the ability for the user to reorder, remove, and add items to the tab bar; this process is referred to as customizing the tab bar. The tab bar delegate receives messages when customizing occurs.
Configuring tab bar items
The items displayed by the tab bar.
func setItems([UITabBarItem]?, animated: Bool)
Sets the items on the tab bar, optionally animating any changes into position.
var selectedItem: UITabBarItem?
The currently selected item on the tab bar.
Customizing tab bar appearance
var standardAppearance: UITabBarAppearance
The appearance settings for a standard-height tab bar.
var scrollEdgeAppearance: UITabBarAppearance?
The appearance settings for the tab bar when the edge of scrollable content aligns with the edge of the tab bar.
var leadingAccessoryView: UIView
The view at the leading edge of a tab bar on tvOS.
var trailingAccessoryView: UIView
The view at the trailing edge of a tab bar on tvOS.
var isTranslucent: Bool
A Boolean value that indicates whether the tab bar is translucent.
Customize appearance information directly on the tab bar object.
Supporting user customization of tab bars
func beginCustomizingItems([UITabBarItem])
Presents a standard interface that lets the user customize the contents of the tab bar.
Dismisses the standard interface used to customize the tab bar.
var isCustomizing: Bool
A Boolean value indicating whether the user is currently customizing the tab bar.
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCopyableCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUISpringLoadedInteractionSupportingUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Container view controllers
Creating a custom container view controller
Create a composite interface by combining content from one or more view controllers with other custom views.
class UISplitViewController
A container view controller that implements a hierarchical interface.
class UINavigationController
A container view controller that defines a stack-based scheme for navigating hierarchical content.
class UINavigationBar
Navigational controls that display in a bar along the top of the screen, usually in conjunction with a navigation controller.
class UINavigationItem
The items that a navigation bar displays when the associated view controller is visible.
class UITabBarController
A container view controller that manages a multiselection interface, where the selection determines which child view controller to display.
class UITabBarItem
An object that describes an item in a tab bar.
class UITab
An object that manages a tab in a tab bar.
class UITabAccessory Beta
class UISearchTab
A tab subclass that represents the system’s search tab.
class UITabGroup
An object that manages a collection of tab objects.
class UIPageViewController
A container view controller that manages navigation between pages of content, where a subview controller manages each page.
https://developer.apple.com/documentation/uikit/uitabbaritem
- UIKit
- UITabBarItem
Class
UITabBarItem
An object that describes an item in a tab bar.
tvOS
@MainActor class UITabBarItem
Overview
A tab bar item is a segment of a tab bar that represents a specific section of your app. A tab bar displays one or more items that allow the user to switch between the different sections. The user can select one item at a time.
The most common approach for displaying a tab bar is to use a tab bar controller. The controller’s tab bar displays an item for each view controller you provide when you set the viewControllers property or call the setViewControllers(_:animated:) method. You’re responsible for supplying the tab bar items. Do this by setting each view controller’s tabBarItem property. When the user selects an item, the tab bar controller displays its view controller. For more information, see UITabBarController.
You can also use a tab bar independent of a tab bar controller. After creating a tab bar, add it to your view hierarchy. Provide the items by setting the tab bar’s items property or by using the setItems(_:animated:) method. In this configuration, you’re responsible for updating the view hierarchy to display the correct content. Use UITabBarDelegate to know when the selection changes. For more information, see UITabBar.
The system provides several tab bar items for common use cases. If you need a custom item, create one with a title and an image. You can further customize the item by providing an alternate image that appears when the user selects it. By default, the item doesn’t display the images you provide. Instead, it generates new images from the alpha values of your images and tints them. To prevent this, provide images that use the UIImage.RenderingMode.alwaysOriginal rendering mode.
An item can adjust its appearance when in certain conditions. For example, you can specify different appearances for inline and compact inline layouts or for when the item’s state changes. To do this, set the item’s standardAppearance property. If you don’t want this behavior, you can set the individual properties on the item instead.
A tab bar item can display a supplementary value in a badge that provides extra information to the user. For example, the Phone app uses a badge’s value to display the number of missed calls. You can customize the badge’s appearance, including its background color and text attributes.
Topics
Creating a tab bar item
convenience init(tabBarSystemItem: UITabBarItem.SystemItem, tag: Int)
Creates a tab bar item using a system-provided configuration.
convenience init(title: String?, image: UIImage?, tag: Int)
Creates a tab bar item that displays a title and an image.
convenience init(title: String?, image: UIImage?, selectedImage: UIImage?)
Creates a tab bar item that toggles the image it displays when its selected state changes.
init()
Creates a tab bar item with a default configuration.
init?(coder: NSCoder)
Creates a tab bar item from a serialized instance.
enum SystemItem
Constants that represent the system tab bar items.
Configuring the item’s appearance
var selectedImage: UIImage?
The source image the item uses to generate its selected image.
var standardAppearance: UITabBarAppearance?
The appearance settings for a tab bar.
var scrollEdgeAppearance: UITabBarAppearance?
The appearance settings for the tab bar when the edge of scrollable content aligns with the edge of the tab bar.
var titlePositionAdjustment: UIOffset
The offset to apply to the title’s position.
Configuring the item’s badge
var badgeValue: String?
The text that the item’s badge displays.
var badgeColor: UIColor?
The background color of the item’s badge.
func setBadgeTextAttributes([NSAttributedString.Key : Any]?, for: UIControl.State)
Registers text attributes that the badge uses for the specified state.
Returns the badge’s text attributes for the specified state.
Relationships
Inherits From
UIBarItem
Conforms To
CVarArgCopyableCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolSendableSendableMetatypeUIAccessibilityIdentificationUIAppearanceUIPopoverPresentationControllerSourceItemUISpringLoadedInteractionSupporting
See Also
Container view controllers
Creating a custom container view controller
Create a composite interface by combining content from one or more view controllers with other custom views.
class UISplitViewController
A container view controller that implements a hierarchical interface.
class UINavigationController
A container view controller that defines a stack-based scheme for navigating hierarchical content.
class UINavigationBar
Navigational controls that display in a bar along the top of the screen, usually in conjunction with a navigation controller.
class UINavigationItem
The items that a navigation bar displays when the associated view controller is visible.
class UITabBarController
A container view controller that manages a multiselection interface, where the selection determines which child view controller to display.
class UITabBar
A control that displays one or more buttons in a tab bar for selecting between different subtasks, views, or modes in an app.
class UITab
An object that manages a tab in a tab bar.
class UITabAccessory Beta
class UISearchTab
A tab subclass that represents the system’s search tab.
class UITabGroup
An object that manages a collection of tab objects.
class UIPageViewController
A container view controller that manages navigation between pages of content, where a subview controller manages each page.
https://developer.apple.com/documentation/uikit/uibarpositioning
- UIKit
- UIBarPositioning
Protocol
UIBarPositioning
A set of methods for defining the positioning of bars in iOS apps.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor protocol UIBarPositioning : NSObjectProtocol
Overview
Bars can be positioned at the bottom of their enclosing view, at the top of their enclosing view, or at both the top of their enclosing view and also the top of the screen. In this last case, the bar will abut the status bar displayed by the system. Bars in this position need to have their background extend above their own frame to the top of the screen. This allows the background to show through the status bar.
The classes that implement bars have paired methods to set a background for a given position and set of metrics. These are named similar to the following: backgroundImage(for:barMetrics:) and setBackgroundImage(_:for:barMetrics:). Use these methods to set an appropriate background image for the different possible bar positions and metrics.
Topics
Accessing the bar position
var barPosition: UIBarPosition
The position of the bar.
Required
Constants
enum UIBarMetrics
Constants to specify metrics to use for appearance.
enum UIBarPosition
Constants to identify the position of a bar.
Relationships
Inherits From
NSObjectProtocol
Conforming Types
UINavigationBarUISearchBarUIToolbar
See Also
Bars
class UIBarItem
An abstract superclass for items that you can add to a bar that appears at the bottom of the screen.
class UIBarButtonItem
A specialized button for placement on a toolbar, navigation bar, or shortcuts bar.
class UIBarButtonItemGroup
A group of one or more bar button items for placement on a navigation bar or shortcuts bar.
class UINavigationBar
Navigational controls that display in a bar along the top of the screen, usually in conjunction with a navigation controller.
class UISearchBar
A specialized view for receiving search-related information from the user.
class UIToolbar
A control that displays one or more buttons along the bottom edge of your interface.
class UITabBar
A control that displays one or more buttons in a tab bar for selecting between different subtasks, views, or modes in an app.
class UITabBarItem
An object that describes an item in a tab bar.
protocol UIBarPositioningDelegate
A set of methods that support the positioning of a bar that conforms to the UIBarPositioning protocol.
https://developer.apple.com/documentation/uikit/uibarpositioningdelegate
- UIKit
- UIBarPositioningDelegate
Protocol
UIBarPositioningDelegate
A set of methods that support the positioning of a bar that conforms to the UIBarPositioning protocol.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor protocol UIBarPositioningDelegate : NSObjectProtocol
Overview
Navigation bars, toolbars, and search bars all have delegates that support the UIBarPositioning protocol. The delegate can use the method of this protocol to specify the bar’s position when that bar is moved to a window. The UINavigationBarDelegate, UISearchBarDelegate, and UIToolbarDelegate protocols extend this protocol to allow for the positioning of those bars on the screen.
Topics
Positioning Bars
Asks the delegate for the position of the specified bar in its new window.
Relationships
Inherits From
NSObjectProtocol
Inherited By
UINavigationBarDelegateUISearchBarDelegateUIToolbarDelegate
See Also
Bars
class UIBarItem
An abstract superclass for items that you can add to a bar that appears at the bottom of the screen.
class UIBarButtonItem
A specialized button for placement on a toolbar, navigation bar, or shortcuts bar.
class UIBarButtonItemGroup
A group of one or more bar button items for placement on a navigation bar or shortcuts bar.
class UINavigationBar
Navigational controls that display in a bar along the top of the screen, usually in conjunction with a navigation controller.
class UISearchBar
A specialized view for receiving search-related information from the user.
class UIToolbar
A control that displays one or more buttons along the bottom edge of your interface.
class UITabBar
A control that displays one or more buttons in a tab bar for selecting between different subtasks, views, or modes in an app.
class UITabBarItem
An object that describes an item in a tab bar.
protocol UIBarPositioning
A set of methods for defining the positioning of bars in iOS apps.
https://developer.apple.com/documentation/uikit/uilargecontentviewerinteraction
- UIKit
- UILargeContentViewerInteraction
Class
UILargeContentViewerInteraction
An interaction that enables a gesture to present the large content viewer for cases when supporting the largest dynamic type sizes isn’t appropriate.
@MainActor class UILargeContentViewerInteraction
Overview
Don’t use the large content viewer as a replacement for proper Dynamic Type support. For example, Dynamic Type allows items in a list to grow or shrink vertically to accommodate the user’s preferred font size. Rely on the large content viewer only in situations where items must remain small due to unavoidable design constraints. For example, buttons in a tab bar remain small to leave more room for the main app content.
For more information about allowing your app’s content to adjust to varying font sizes, see Add Dynamic Type support and the Human Interface Guidelines.
Topics
Creating large content viewer interactions
init(delegate: (any UILargeContentViewerInteractionDelegate)?)
Creates an interaction object with the specified delegate.
Customizing large content viewer interactions
var delegate: (any UILargeContentViewerInteractionDelegate)?
An object that can fine-tune the large content viewer interactions, especially in the presence of other gesture recognizers.
var gestureRecognizerForExclusionRelationship: UIGestureRecognizer
A gesture recognizer that you can use to set up simultaneous recognition or failure relationships with other gesture recognizers.
Detecting the large content viewer
class var isEnabled: Bool
A Boolean value that indicates whether the large content viewer is enabled on the device.
class let enabledStatusDidChangeNotification: NSNotification.Name
A notification the system posts when it enables or disables the large content viewer.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendableUIInteraction
See Also
Content viewer
protocol UILargeContentViewerInteractionDelegate
An object that customizes the behavior of the large content viewer interactions.
protocol UILargeContentViewerItem
Methods that provide details about how to display your custom content in the large content viewer.
https://developer.apple.com/documentation/uikit/uilargecontentviewerinteractiondelegate
- UIKit
- UILargeContentViewerInteractionDelegate
Protocol
UILargeContentViewerInteractionDelegate
An object that customizes the behavior of the large content viewer interactions.
@MainActor protocol UILargeContentViewerInteractionDelegate : NSObjectProtocol
Topics
Customizing large content viewer interactions
func largeContentViewerInteraction(UILargeContentViewerInteraction, didEndOn: (any UILargeContentViewerItem)?, at: CGPoint)
Performs an action when the large content viewer gesture ends at the location of the specified item.
Identifies the large content viewer item for the specified interaction and location.
Specifies which view controller should display the large content viewer.
Relationships
Inherits From
NSObjectProtocol
See Also
Content viewer
class UILargeContentViewerInteraction
An interaction that enables a gesture to present the large content viewer for cases when supporting the largest dynamic type sizes isn’t appropriate.
protocol UILargeContentViewerItem
Methods that provide details about how to display your custom content in the large content viewer.
https://developer.apple.com/documentation/uikit/uilargecontentvieweritem
- UIKit
- UILargeContentViewerItem
Protocol
UILargeContentViewerItem
Methods that provide details about how to display your custom content in the large content viewer.
@MainActor protocol UILargeContentViewerItem : NSObjectProtocol
Topics
Integrating with the large content viewer
var showsLargeContentViewer: Bool
A Boolean value that indicates whether or not to show the item in the large content viewer.
Required
Configuring display properties
var largeContentTitle: String?
A string that describes an item to display in the large content viewer.
var largeContentImage: UIImage?
An image that represents an item to display in the large content viewer.
var largeContentImageInsets: UIEdgeInsets
Insets to adjust the position of the item’s image so it appears visually centered in the large content viewer.
var scalesLargeContentImage: Bool
A Boolean value that indicates whether the view scales the item’s image to a larger size or not.
Relationships
Inherits From
NSObjectProtocol
Conforming Types
UIActionSheetUIActivityIndicatorViewUIAlertViewUIBackgroundExtensionViewUIButtonUICalendarViewUICollectionReusableViewUICollectionViewUICollectionViewCellUICollectionViewListCellUIColorWellUIContentUnavailableViewUIControlUIDatePickerUIEventAttributionViewUIImageViewUIInputViewUILabelUIListContentViewUINavigationBarUIPageControlUIPasteControlUIPickerViewUIPopoverBackgroundViewUIProgressViewUIRefreshControlUIScrollViewUISearchBarUISearchTextFieldUISegmentedControlUISliderUIStackViewUIStandardTextCursorViewUIStepperUISwitchUITabBarUITableViewUITableViewCellUITableViewHeaderFooterViewUITextFieldUITextViewUIToolbarUIViewUIVisualEffectViewUIWebViewUIWindow
See Also
Content viewer
class UILargeContentViewerInteraction
An interaction that enables a gesture to present the large content viewer for cases when supporting the largest dynamic type sizes isn’t appropriate.
protocol UILargeContentViewerInteractionDelegate
An object that customizes the behavior of the large content viewer interactions.
https://developer.apple.com/documentation/uikit/uieventattributionview
- UIKit
- UIEventAttributionView
Class
UIEventAttributionView
An overlay view that verifies user interaction for Web AdAttributionKit.
@MainActor class UIEventAttributionView
Overview
Web AdAttributionKit (formerly known as Private Click Measurement, or PCM) is a proposed web standard that allows external websites to measure when external links, such as ads, result in a conversion. The external website decides what constitutes a conversion, but it’s often the result of the user making a purchase or signing up for a service. Web AdAttributionKit doesn’t send any user-identifiable information to the remote server, so it protects user privacy, while providing websites the ability to measure the effectiveness of their ad campaigns.
Apps running in iOS 17.4 or later can use AdAttributionKit to record click-through impressions on custom rendered ad content using a UIEventAttributionView. For more information about click-through in AdAttributionKit, see Presenting ads in your app.
Apps running in iOS 14.5 or later can take advantage of Web AdAttributionKit by sending event attribution data to the browser when opening an external link. If the linked website reports a conversion within 7 days, the browser forwards your appʼs Web AdAttributionKit data to a specified remote server sometime between 24 and 48 hours after the reported conversion.
You can’t subclass UIEventAttributionView.
For more information on the proposed Web AdAttributionKit web standard, see Introducing Private Click Measurement and Private Click Measurement Draft Community Group Report.
Verify user interaction
Event attribution views overlay other UIKit controls to ensure that either handling a tap with AdAttributionKit or opening an external link with Web AdAttributionKit data only happens as the result of a user tap. The system doesn’t handle the tap or send event attribution data to the browser unless a UIEventAttributionView exists above the tapped control.
Create an event attribution view
Place an event attribution view above any view that launches external links with event attribution data and make sure there are no other overlapping views above the event attribution view that might intercept taps. UIEventAttributionView doesn’t consume tap events, so the behavior of any control below one in the view hierarchy isn’t affected.
If multiple views or controls in your app can launch an external link using Web AdAttributionKit, use a separate UIEventAttributionView to overlay each control. While you can use a single UIEventAttributionView to validate more than one control, attribution views that cover large portions of the screen may impact performance because the system must validate all user interactions that pass through the attribution view.
Here’s how to add an event attribution view to an in-app advertisement:
// Create an event attribution view. let eventAttributionView = UIEventAttributionView()
// Place it over the ad view.
eventAttributionView.translatesAutoresizingMaskIntoConstraints = false
adView.addSubview(eventAttributionView)
NSLayoutConstraint.activate([
adView.topAnchor.constraint(equalTo: eventAttributionView.topAnchor),
adView.leadingAnchor.constraint(equalTo: eventAttributionView.leadingAnchor),
adView.trailingAnchor.constraint(equalTo: eventAttributionView.trailingAnchor),
adView.bottomAnchor.constraint(equalTo: eventAttributionView.bottomAnchor)
])
// Create an event attribution view. UIEventAttributionView *eventAttributionView = [[UIEventAttributionView alloc] init];
// Place it over the ad view.
eventAttributionView.translatesAutoresizingMaskIntoConstraints = NO;
[adView addSubview:eventAttributionView];
[NSLayoutConstraint activateConstraints: @[
[adView.topAnchor constraintEqualToAnchor:eventAttributionView.topAnchor],
[adView.leadingAnchor constraintEqualToAnchor:eventAttributionView.leadingAnchor],
[adView.trailingAnchor constraintEqualToAnchor:eventAttributionView.trailingAnchor],
[adView.bottomAnchor constraintEqualToAnchor:eventAttributionView.bottomAnchor]
]];
For more information on sending Web AdAttributionKit event attribution data to the browser when opening an external link, see UIEventAttribution.
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Private Click Measurement (PCM)
class UIEventAttribution
An object that contains event attribution information for Web AdAttributionKit.
NSAdvertisingAttributionReportEndpoint
The URL where Private Click Measurement and SKAdNetwork send attribution information.
https://developer.apple.com/documentation/uikit/uieventattribution
- UIKit
- UIEventAttribution
Class
UIEventAttribution
An object that contains event attribution information for Web AdAttributionKit.
@MainActor class UIEventAttribution
Overview
Apps use event attribution objects to send data to the browser when opening an external website that supports Web AdAttributionKit (formerly known as Private Click Measurement, or PCM). For more information on the proposed PCM web standard, see Introducing Private Click Measurement and Private Click Measurement Draft Community Group Report.
You can’t subclass UIEventAttribution.
Define an endpoint
In order to use Web AdAttributionKit, your app defines an Info.plist key called NSAdvertisingAttributionReportEndpoint that contains the URL to which the browser sends event attribution data. When an externally linked website reports that a conversion has occurred, the browser forwards your app’s event attribution data to the endpoint specified in the Info.plist. If your app’s Info.plist doesn’t contain this key, the browser won’t be able to forward the Web AdAttributionKit data when a conversion occurs.
Send event attribution data to the browser only when your app opens an external link as a result of a user tapping a control that sits below a UIEventAttributionView in the app’s view hierarchy. The event attribution view verifies that the user tapped a control. If that control doesn’t sit below an event attribution view, the system won’t send the Web AdAttributionKit data to the browser when opening the external link.
Create an event attribution data object
Here’s how you create a UIEventAttribution object:
let adURL = URL(string: "https://shop.example/tabletStandDeluxe.html")! let eventAttribution = UIEventAttribution(sourceIdentifier: 4, destinationURL: adURL, sourceDescription: "Banner ad for Tablet Stand Deluxe.", purchaser: "Shop Example, Inc.")
NSURL *adURL = [NSURL URLWithString:@"https://shop.example/tabletStandDeluxe.html"];
UIEventAttribution *eventAttribution = [[UIEventAttribution alloc]
initWithSourceIdentifier:4
destinationURL:adURL
sourceDescription:@"Banner ad for Tablet Stand Deluxe."
purchaser:@"Shop Example, Inc."];
Send event attribution data to the browser
Once you create a UIEventAttribution object, send it to the browser when your app opens a URL as the result of a user tap. If the external website reports a conversion within 7 days, the browser forwards the data from the UIEventAttribution object to the specified remote server sometime between 24 and 48 hours after the conversion.
There are two different ways to send event attribution data when your app opens an external link, depending on whether your app uses UIScene or UIApplication for life cycle management. For more information on application life cycle management, see Managing your app’s life cycle.
If your app uses UIScene-based life cycle management, create a UIScene.OpenExternalURLOptions object, assign the event attribution object you created to its eventAttribution property, and call open(_:options:completionHandler:):
let sceneOpenURLOptions = UIScene.OpenExternalURLOptions() sceneOpenURLOptions.eventAttribution = eventAttribution
self.view.window?.windowScene?.open(adURL, options: sceneOpenURLOptions, completionHandler: nil)
UISceneOpenExternalURLOptions *sceneOpenURLOptions = [[UISceneOpenExternalURLOptions alloc] init];
sceneOpenURLOptions.eventAttribution = eventAttribution;
[self.view.window.windowScene openURL:adURL
options:sceneOpenURLOptions
completionHandler:^(BOOL success) {
if (success == NO) {
// Handle error
}
}];
If your app uses UIApplication-based life cycle management, create a dictionary that contains the eventAttribution key with the UIEventAttribution object you created as its value, and call open(_:options:completionHandler:), passing the dictionary using the options parameter.
let appOpenURLOptions: [UIApplication.OpenExternalURLOptionsKey : Any] = [
.eventAttribution: eventAttribution
]
UIApplication.shared.open(adURL,
options: appOpenURLOptions,
completionHandler: nil)
[[UIApplication sharedApplication] openURL:adURL
options:appOpenURLOptions
completionHandler:^(BOOL success) {
if (success == NO) {
// Handle error
}
}];
Send event attribution data to SFSafariViewController
If your app displays a web page in SFSafariViewController after a person taps an ad, add a UIEventAttributionView subview to the ad view or control in order to measure taps. When a person taps the ad, follow these steps:
-
Create an
SFSafariViewController.Configurationobject. -
Assign the
UIEventAttributionobject you created to theeventAttributionproperty of theSFSafariViewController.Configurationobject. -
Initialize an
SFSafariViewControllerinstance with the configuration object, and present it.SFSafariViewControllervalidates that a tap on aUIEventAttributionViewinitiated the navigation to the webpage. If not, it discards the attribution data.
Topics
Creating event attribution objects
init(sourceIdentifier: UInt8, destinationURL: URL, sourceDescription: String, purchaser: String)
Initializes a new event attribution object.
Setting attribution details
var destinationURL: URL
The destination URL to attribute.
var purchaser: String
The entity that purchased the ad or content.
var reportEndpoint: URL?
The URL that receives attribution data.
var sourceDescription: String
A string describing the source tapped to launch the external link.
var sourceIdentifier: UInt8
A number that identifies the source of the attribution.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCopyingNSObjectProtocolSendable
See Also
Private Click Measurement (PCM)
class UIEventAttributionView
An overlay view that verifies user interaction for Web AdAttributionKit.
NSAdvertisingAttributionReportEndpoint
The URL where Private Click Measurement and SKAdNetwork send attribution information.
https://developer.apple.com/documentation/uikit/using-swiftui-with-uikit
- UIKit
- Views and controls
- Using SwiftUI with UIKit
Sample Code
Using SwiftUI with UIKit
Learn how to incorporate SwiftUI views into a UIKit app.
Download
Xcode 13.4+
Overview
https://developer.apple.com/documentation/uikit/uioffset
- UIKit
- UIOffset
Structure
UIOffset
A structure that specifies an amount to offset a position.
iOSiPadOSMac CatalysttvOSvisionOS
struct UIOffset
Overview
The components are positive for right or down, negative for left or up.
See also Initializing offsets and zero.
Topics
Initializing offsets
init(horizontal: CGFloat, vertical: CGFloat)
Creates an offset structure from the given components.
init()
Creates an offset structure.
Getting the offset values
var horizontal: CGFloat
The amount of horizontal offset from a position.
var vertical: CGFloat
The amount of vertical offset from a position.
Comparing offsets
Returns a Boolean value that indicates whether two offsets are equal.
Deprecated
Converting to and from strings
Returns a string formatted to contain the data from an offset structure.
Returns a UIKit offset structure corresponding to the data in a given string.
Getting the empty offset value
static let zero: UIOffset
An offset structure with no offset in the horizontal and vertical directions.
Relationships
Conforms To
BitwiseCopyableCopyableDecodableEncodableEquatableSendableSendableMetatype
See Also
Related types
struct UIAxis
A structure that specifies the layout axes.
struct UIEdgeInsets
The inset distances for views.
struct NSDirectionalEdgeInsets
The inset distances for views, taking the user interface layout direction into account.
struct NSDirectionalRectEdge
Constants that specify an edge or a set of edges, taking the user interface layout direction into account.
enum NSRectAlignment
Constants that specify alignment to an edge or a set of edges depending on the user interface layout direction.
struct UIDirectionalRectEdge
Macros that UIKit defines.
https://developer.apple.com/documentation/uikit/uiaxis
- UIKit
- UIAxis
Structure
UIAxis
A structure that specifies the layout axes.
struct UIAxis
Topics
Constants
static var horizontal: UIAxis
A value that represents the horizontal axis.
static var vertical: UIAxis
A value that represents the vertical axis.
static var both: UIAxis
A value that represents both axes.
Initializers
init(rawValue: UInt)
Creates an axis with the specified raw value.
Relationships
Conforms To
BitwiseCopyableEquatableExpressibleByArrayLiteralOptionSetRawRepresentableSendableSendableMetatypeSetAlgebra
See Also
Related types
struct UIOffset
A structure that specifies an amount to offset a position.
struct UIEdgeInsets
The inset distances for views.
struct NSDirectionalEdgeInsets
The inset distances for views, taking the user interface layout direction into account.
struct NSDirectionalRectEdge
Constants that specify an edge or a set of edges, taking the user interface layout direction into account.
enum NSRectAlignment
Constants that specify alignment to an edge or a set of edges depending on the user interface layout direction.
struct UIDirectionalRectEdge
Deprecated
Macros that UIKit defines.
https://developer.apple.com/documentation/uikit/uiedgeinsets
- UIKit
- UIEdgeInsets
Structure
UIEdgeInsets
The inset distances for views.
iOSiPadOSMac CatalysttvOSvisionOS
struct UIEdgeInsets
Overview
Edge inset values are applied to a rectangle to shrink or expand the area represented by that rectangle. Typically, edge insets are used during view layout to modify the view’s frame. Positive values cause the frame to be inset (or shrunk) by the specified amount. Negative values cause the frame to be outset (or expanded) by the specified amount.
See also init(top:left:bottom:right:) and zero.
Topics
Creating edge insets
init(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat)
Creates an edge insets structure with the specified edges.
init()
Initializes the edge insets structure to default values.
Getting the edge values
var bottom: CGFloat
The bottom edge inset value.
var left: CGFloat
The left edge inset value.
var right: CGFloat
The right edge inset value.
var top: CGFloat
The top edge inset value.
Converting to and from strings
Returns a string formatted to contain the data from an edge insets structure.
Returns a UIKit edge insets structure based on the data in the specified string.
Getting the empty edge insets
static let zero: UIEdgeInsets
An edge insets struct whose top, left, bottom, and right fields are all set to 0.
Comparing edge insets
Returns a Boolean value indicating whether the two edge insets are the same.
Deprecated
Relationships
Conforms To
BitwiseCopyableCopyableDecodableEncodableEquatableSendableSendableMetatype
See Also
Related types
struct UIOffset
A structure that specifies an amount to offset a position.
struct UIAxis
A structure that specifies the layout axes.
struct NSDirectionalEdgeInsets
The inset distances for views, taking the user interface layout direction into account.
struct NSDirectionalRectEdge
Constants that specify an edge or a set of edges, taking the user interface layout direction into account.
enum NSRectAlignment
Constants that specify alignment to an edge or a set of edges depending on the user interface layout direction.
struct UIDirectionalRectEdge
Macros that UIKit defines.
https://developer.apple.com/documentation/uikit/nsdirectionaledgeinsets
https://developer.apple.com/documentation/uikit/nsdirectionalrectedge
- UIKit
- NSDirectionalRectEdge
Structure
NSDirectionalRectEdge
Constants that specify an edge or a set of edges, taking the user interface layout direction into account.
struct NSDirectionalRectEdge
Topics
Constants
static var top: NSDirectionalRectEdge
The top edge.
static var leading: NSDirectionalRectEdge
The leading edge.
static var bottom: NSDirectionalRectEdge
The bottom edge.
static var trailing: NSDirectionalRectEdge
The trailing edge.
static var all: NSDirectionalRectEdge
All edges.
Initializers
init(rawValue: UInt)
Creates an edge with the specified raw value.
Relationships
Conforms To
BitwiseCopyableEquatableExpressibleByArrayLiteralOptionSetRawRepresentableSendableSendableMetatypeSetAlgebra
See Also
Related types
struct UIOffset
A structure that specifies an amount to offset a position.
struct UIAxis
A structure that specifies the layout axes.
struct UIEdgeInsets
The inset distances for views.
struct NSDirectionalEdgeInsets
The inset distances for views, taking the user interface layout direction into account.
enum NSRectAlignment
Constants that specify alignment to an edge or a set of edges depending on the user interface layout direction.
struct UIDirectionalRectEdge
Deprecated
Macros that UIKit defines.
https://developer.apple.com/documentation/uikit/nsrectalignment
https://developer.apple.com/documentation/uikit/uidirectionalrectedge
- UIKit
- UIDirectionalRectEdge Deprecated
Structure
UIDirectionalRectEdge
Constants that specify an edge or a set of edges, taking the user interface layout direction into account.
iOS 13.0–13.0DeprecatediPadOS 13.0–13.0DeprecatedMac Catalyst 13.1–13.1DeprecatedtvOS 13.0–13.0DeprecatedwatchOS 6.0–6.0Deprecated
struct UIDirectionalRectEdge
Topics
Constants
static var top: UIDirectionalRectEdge
The top edge.
static var leading: UIDirectionalRectEdge
The leading edge.
static var bottom: UIDirectionalRectEdge
The bottom edge.
static var trailing: UIDirectionalRectEdge
The trailing edge.
static var all: UIDirectionalRectEdge
All edges.
Initializers
init(rawValue: UInt)
Creates an edge with the specified raw value.
Relationships
Conforms To
BitwiseCopyableEquatableExpressibleByArrayLiteralOptionSetRawRepresentableSendableSendableMetatypeSetAlgebra
See Also
Related types
struct UIOffset
A structure that specifies an amount to offset a position.
struct UIAxis
A structure that specifies the layout axes.
struct UIEdgeInsets
The inset distances for views.
struct NSDirectionalEdgeInsets
The inset distances for views, taking the user interface layout direction into account.
struct NSDirectionalRectEdge
enum NSRectAlignment
Constants that specify alignment to an edge or a set of edges depending on the user interface layout direction.
Macros that UIKit defines.
https://developer.apple.com/documentation/uikit/uikit-macros
https://developer.apple.com/documentation/uikit/uicontrol)
https://developer.apple.com/documentation/uikit/uikit-catalog-creating-and-customizing-views-and-controls).
.#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/collection-views)
https://developer.apple.com/documentation/uikit/table-views)
https://developer.apple.com/documentation/uikit/uistackview)
https://developer.apple.com/documentation/uikit/uiscrollview)
https://developer.apple.com/documentation/uikit/uiactivityindicatorview)
https://developer.apple.com/documentation/uikit/uicalendarview)
https://developer.apple.com/documentation/uikit/uicontentunavailableview)
https://developer.apple.com/documentation/uikit/uiimageview)
https://developer.apple.com/documentation/uikit/uipickerview)
https://developer.apple.com/documentation/uikit/uiprogressview)
https://developer.apple.com/documentation/uikit/uiwebview)
https://developer.apple.com/documentation/uikit/responding-to-control-based-events-using-target-action)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uibutton)
https://developer.apple.com/documentation/uikit/uicolorwell)
https://developer.apple.com/documentation/uikit/uidatepicker)
https://developer.apple.com/documentation/uikit/uipagecontrol)
https://developer.apple.com/documentation/uikit/uisegmentedcontrol)
https://developer.apple.com/documentation/uikit/uislider)
https://developer.apple.com/documentation/uikit/uistepper)
https://developer.apple.com/documentation/uikit/uiswitch)
https://developer.apple.com/documentation/uikit/uilabel)
https://developer.apple.com/documentation/uikit/uitextfield)
https://developer.apple.com/documentation/uikit/uitextview)
https://developer.apple.com/documentation/uikit/drag-and-drop-customization)
https://developer.apple.com/documentation/uikit/uisearchtextfield)
https://developer.apple.com/documentation/uikit/uisearchtoken)
https://developer.apple.com/documentation/uikit/uisearchtextfielddelegate)
https://developer.apple.com/documentation/uikit/uivisualeffect)
https://developer.apple.com/documentation/uikit/uivisualeffectview)
https://developer.apple.com/documentation/uikit/uivibrancyeffect)
https://developer.apple.com/documentation/uikit/uiblureffect)
https://developer.apple.com/documentation/uikit/uibaritem)
https://developer.apple.com/documentation/uikit/uibarbuttonitem)
https://developer.apple.com/documentation/uikit/uibarbuttonitemgroup)
https://developer.apple.com/documentation/uikit/uinavigationbar)
https://developer.apple.com/documentation/uikit/uisearchbar)
https://developer.apple.com/documentation/uikit/uitoolbar)
https://developer.apple.com/documentation/uikit/uitabbar)
https://developer.apple.com/documentation/uikit/uitabbaritem)
https://developer.apple.com/documentation/uikit/uibarpositioning)
https://developer.apple.com/documentation/uikit/uibarpositioningdelegate)
https://developer.apple.com/documentation/uikit/uilargecontentviewerinteraction)
https://developer.apple.com/documentation/uikit/uilargecontentviewerinteractiondelegate)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uilargecontentvieweritem)
https://developer.apple.com/documentation/uikit/uieventattributionview)
https://developer.apple.com/documentation/uikit/uieventattribution)
https://developer.apple.com/documentation/uikit/using-swiftui-with-uikit)
https://developer.apple.com/documentation/uikit/uioffset)
https://developer.apple.com/documentation/uikit/uiaxis)
https://developer.apple.com/documentation/uikit/uiedgeinsets)
https://developer.apple.com/documentation/uikit/nsdirectionaledgeinsets)
https://developer.apple.com/documentation/uikit/nsdirectionalrectedge)
https://developer.apple.com/documentation/uikit/nsrectalignment)
https://developer.apple.com/documentation/uikit/uidirectionalrectedge)
https://developer.apple.com/documentation/uikit/uikit-macros)
https://developer.apple.com/documentation/uikit/uimanageddocument
- UIKit
- UIManagedDocument
Class
UIManagedDocument
A managed document object that integrates with Core Data.
@MainActor class UIManagedDocument
Overview
UIManagedDocument is a concrete subclass of UIDocument. When you initialize a managed document, you specify the URL for the document location. The document object then creates a Core Data stack to use to access the document’s persistent store using a managed object model from the app’s main bundle. UIManagedDocument performs all the basic setup you need for Core Data, and in some cases you may use instances of the class directly (without a need to subclass). You can supply configuration options for the creation of the coordinator using persistentStoreOptions, and for the model using modelConfiguration. You can also perform additional customization by creating a subclass of UIManagedDocument:
-
Override
persistentStoreNameto customize the name of the persistent store file inside the document’s file package. -
Override
managedObjectModelto customize creation of the managed object model.
You do this if, for example, your app supports multiple document types, each of which uses a different model. You want to ensure that the models aren’t merged for each document class.
-
Override
persistentStoreType(forFileType:)to customize the type of persistent store used by a document. -
Override
configurePersistentStoreCoordinator(for:ofType:modelConfiguration:storeOptions:)to customize the loading or creation of a persistent store.
Handling errors
To enable your app to observe and handle errors in saving and validating a managed document, you must subclass the UIManagedDocument class and override one or both of the following two inherited methods from the UIDocument class:
-
handleError(_:userInteractionPermitted:) -
finishedHandlingError(_:recovered:)
Overriding is required because otherwise, the only information your app receives on error is the stateChangedNotification notification, which doesn’t contain a userInfo dictionary and so doesn’t convey specific error information.
Topics
Managing the Core Data stack
Creates or loads the document’s persistent store.
var managedObjectContext: NSManagedObjectContext
The document’s managed object context.
var managedObjectModel: NSManagedObjectModel
The document’s managed object model.
var persistentStoreOptions: [AnyHashable : Any]?
Options used when creating the document’s persistent store.
var modelConfiguration: String?
A model configuration name to be passed when configuring the persistent store.
Returns the Core Data store type for a given document file type.
Customizing read and write operations
func readAdditionalContent(from: URL) throws
Handles reading non-Core Data content in the additional content directory in the document’s file package.
Handles writing non-Core Data content to the additional content directory in the document’s file package.
func writeAdditionalContent(Any, to: URL, originalContentsURL: URL?) throws
Handles writing non-Core Data content to the document’s file package.
Naming the persistent store file
class var persistentStoreName: String
Returns the name for the persistent store file inside the document’s file package.
Relationships
Inherits From
UIDocument
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSFilePresenterNSObjectProtocolProgressReportingSendableSendableMetatypeUIUserActivityRestoring
See Also
Documents
class UIDocument
An abstract base class for managing discrete portions of your app’s data.
Synchronizing documents in the iCloud environment
Manage documents across multiple devices to create a seamless editing and collaboration experience.
https://developer.apple.com/documentation/uikit/synchronizing-documents-in-the-icloud-environment
- UIKit
- Documents, data, and pasteboard
- Synchronizing documents in the iCloud environment
Sample Code
Synchronizing documents in the iCloud environment
Manage documents across multiple devices to create a seamless editing and collaboration experience.
Download
Xcode 12.4+
Overview
As technology advances, more and more people generate their digital assets from different devices, and expect those assets to synchronize seamlessly. To support such use cases, apps need to discover the assets, as well as their changes, from all the devices, and present the user with a consistent view.
This sample demonstrates how to discover and synchronize documents in the iCloud environment, and manage them to achieve high performance and a low memory footprint. These documents can be the digital assets or any user data.
The sample also demonstrates how to publish an iCloud container to iCloud Drive so that the user can access the container’s Documents folder from other apps. Additionally, it shows how to support the Open-in-Place feature, which allows the user to launch an app by tapping a document in Files, and then edit it directly.
Configure the sample code project
Before building the sample, perform the following steps in Xcode:
-
In the General pane of the
SimpleiCloudDocumenttarget, update the Bundle Identifier field with a new identifier. -
In the Signing & Capabilities pane, select the applicable team from the Team drop-down menu to let Xcode automatically manage the provisioning profile. See Assign a project to a team for details.
-
If you prefer to use a different container, select it from the Containers list, specify the container identifier when creating the
MetadataProviderinstance in theviewDidLoadmethod of theMainViewControllerclass. An iCloud container identifier is case-sensitive and must begin with “iCloud.”. -
Find the
NSUbiquitousContainersentry in theInfo.plistfile, and change the iCloud container identifier there as well.
Before running the sample on a device, configure the device as follows:
-
Log in with an Apple ID. For documents to synchronize across devices, the Apple ID must be the same on all devices.
-
Prepare some pictures in the Photo Library to use in the sample.
Publish an iCloud container to iCloud Drive
Publishing an iCloud container to iCloud Drive makes the container’s Documents folder appear in iCloud Drive so the user can access the folder from other apps. Follow these steps to publish a container:
-
Provide the container’s metadata by adding an
NSUbiquitousContainersentry to theInfo.plistfile like the example code below demonstrates. -
Increase the bundle version by changing the Build field in the General pane of the Xcode target, or the
CFBundleVersionentry in theInfo.plistfile. The new value must be larger than the previous value when using thecompare(_:options:range:)method with theNSString.CompareOptions.numericoption to compare, and must only contain numeric (0 – 9) and period (.) characters. The system only updates an app’s iCloud container metadata when detecting a new version, so perform this step every time the metadata changes. -
Make sure the
Documentsfolder exists in the iCloud container and has at least one document.
The NSUbiquitousContainers entry of the sample is as follows:
Support Open-in-Place
The Open-in-Place feature allows the user to launch an app by tapping a document of the type the app owns. After opening it, the app can change the document directly without copying it to the app’s sandbox container. Follow these steps to implement the feature:
-
Declare and export a document type for the app by adding the
CFBundleDocumentTypesandUTExportedTypeDeclarationsInfo.plistentries. Make sure the type conforms to at leastpublic.contentandpublic.datain theUTTypeConformsToentry so that the other system components, likeUIActivityViewController, recognize it. -
Add the
LSSupportsOpeningDocumentsInPlacekey to theInfo.plistfile, and set the value toYES. -
Implement the
scene(_:openURLContexts:)method of theUISceneDelegateprotocol to accept the document.
Apps need to wrap the code that accesses the passed-in URL with the startAccessingSecurityScopedResource and stopAccessingSecurityScopedResource methods if the URL is outside of their sandbox. This sample doesn’t explicitly do that because it accesses the URL via UIDocument, which handles security-scoped bookmarks automatically.
Discover documents in an iCloud container
iOS apps use NSMetadataQuery rather than file system APIs to discover documents in an iCloud container. When an app creates an iCloud document on one device, iCloud first synchronizes the document metadata to the other devices to tell them about the existence of the document. Then, depending on the device types, iCloud may or may not continue to synchronize the document data. For iOS devices, iCloud doesn’t synchronize the document data until an app asks (either explicitly or implicitly). When an iOS app receives a notification that a new document exists, the document data may not physically exist on the local file system, so it isn’t discoverable with file system APIs.
To watch the metadata changes in the iCloud container, the sample creates an NSMetadataQuery object. It uses the following code to configure and start the query to gather the changes of documents that are in the iCloud container and have an .sicd extension name.
metadataQuery.notificationBatchingInterval = 1 metadataQuery.searchScopes = [NSMetadataQueryUbiquitousDataScope, NSMetadataQueryUbiquitousDocumentsScope] metadataQuery.predicate = NSPredicate(format: "%K LIKE %@", NSMetadataItemFSNameKey, "*." + Document.extensionName) metadataQuery.sortDescriptors = [NSSortDescriptor(key: NSMetadataItemFSNameKey, ascending: true)] metadataQuery.start()
A query has two phases when gathering the metadata: the initial phase that collects all currently matching results, and a second phase that gathers live updates. It posts an NSMetadataQueryDidFinishGathering notification when it finishes the first phase, and an NSMetadataQueryDidUpdate notification each time an update occurs. To avoid potential conflicts with the system, disable the query update when accessing the results, and enable it after finishing the access, as the following example shows:
var result = MetadataItem metadataQuery.disableUpdates() if let metadatItems = metadataQuery.results as? [NSMetadataItem] { result = metadataItemList(from: metadatItems) } metadataQuery.enableUpdates() return result }
Manage a large data set
Documents in this sample could potentially contain many images, and the images might be large. To load image data only when necessary, and release the data immediately after using it, the Document class provides public methods for directly accessing the images in the document package. As an example, the following method retrieves a full image asynchronously:
performAsynchronousFileAccess { let imageFileURL = self.fileURL.appendingPathComponent(imageName) let fileCoordinator = NSFileCoordinator(filePresenter: self) fileCoordinator.coordinate(readingItemAt: imageFileURL, options: .withoutChanges, error: nil) { newURL in if let imageData = try? Data(contentsOf: newURL), let image = UIImage(data: imageData) { completionHandler(image) } else { completionHandler(nil) } } } }
When directly manipulating the files in the document package, the sample calls the performAsynchronousFileAccess(_:) method to serialize the file access in the background queue, and uses NSFileCoordinator to coordinate the reading or writing.
Likewise, to avoid the default implementation that loads image data to FileWrapper objects and keeps it in memory, the sample overrides the save(to:for:completionHandler:) method to directly remove or add image files when updating a document.
if saveOperation != .forCreating { print("(#function)") return performAsynchronousFileAccess { let fileCoordinator = NSFileCoordinator(filePresenter: self) fileCoordinator.coordinate(writingItemAt: self.fileURL, options: .forMerging, error: nil) { newURL in let success = self.fulfillUnsavedChanges() self.fileModificationDate = Date() if let completionHandler = completionHandler { DispatchQueue.main.async { completionHandler(success) } } } } } super.save(to: url, for: saveOperation, completionHandler: completionHandler) }
Resolve version conflicts
In the iCloud environment, the user can edit a document from different devices. Depending on networking conditions and the timing of synchronization, that may trigger version conflicts. Apps that provide support for iCloud documents need to resolve these conflicts, and remove the obsolete versions so they don’t consume the user’s iCloud storage.
To create a document conflict with the sample:
-
Run the sample on two iOS devices with Internet connections that use the same Apple ID to log in to iCloud.
-
Create a document with several images on one device, and watch the document synchronize with the other device.
-
Turn on Airplane mode on both devices to disconnect them from the Internet.
-
Change the document on both devices by adding some images on one device, removing some images from the other device, and then saving the changes.
-
Turn off Airplane mode on both devices at the same time to connect them notification, which apps can observe and then implement their conflict resolution strategy.
The sample resolves a conflict by selecting the version that has the most recent modificationDate and removing all others. It uses file coordination to assess the version information of an iCloud document to avoid potential conflicts with the system.
DispatchQueue.global().async { NSFileCoordinator().coordinate(writingItemAt: document.fileURL, options: .contentIndependentMetadataOnly, error: nil) { newURL in let shouldRevert = self.pickLatestVersion(for: newURL) completionHandler?(shouldRevert) } } }
See Also
Documents
class UIDocument
An abstract base class for managing discrete portions of your app’s data.
class UIManagedDocument
A managed document object that integrates with Core Data.
https://developer.apple.com/documentation/uikit/uidocumentviewcontroller
- UIKit
- UIDocumentViewController
Class
UIDocumentViewController
A view controller that manages and presents a document stored locally or in the cloud.
@MainActor class UIDocumentViewController
Mentioned in
Customizing a document-based app’s launch experience
Overview
UIDocumentViewController presents a view that displays a document. It manages opening, saving, and closing the document. You can use UIDocumentViewController to present documents from a UIDocumentBrowserViewController, for instance. When you aren’t presenting documents from a UIDocumentBrowserViewController, UIDocumentViewController displays a button that, when tapped, presents a picker a person can use to choose the document to display.
The document view controller’s document property is an optional UIDocument. While the document property value is nil, the document view controller displays a view depicting an empty state with the message, “No Document”. The empty state provides a prompt that reads “Select a document by tapping the ‘Documents’ button at the top.”
When the document property value is not nil, the document view controller displays the document. You configure the view to display the document in the documentDidOpen() callback method.
The navigation item automatically assigns its title menu, its UIDocumentProperties object, undo and redo buttons, and renameDelegate from information in the document view controller’s document.
UIDocumentViewController also provides sharing and drag and drop support, and key-commands for common actions such as undo and redo.
Subclassing notes
UIDocumentViewController is an abstract base class that is meant to be subclassed. To create a subclass, you override two methods.
-
The system calls
documentDidOpen()when someone opens the document associated with the document view controller, or when an object assigns a previously opened document to the document view controller. -
The system calls
navigationItemDidUpdate()every timeUIDocumentViewControllermakes changes to its navigation item.
Open and close documents
When the document view controller opens the document associated with it, or when an object assigns an already opened document to the document view controller, the system calls documentDidOpen(). You can populate the view controller’s views to display the content of the document in this method:
override func documentDidOpen() { configureViewForCurrentDocument() }
It’s good practice to configure the view in its own method and call that method in both documentDidOpen() and viewDidLoad(). There is no guarantee of the timing between when the system calls documentDidOpen() and when the system loads the view controller’s view, so check that the view loaded and the document opened before configuring your views.
override func viewDidLoad() { super.viewDidLoad() configureViewForCurrentDocument() }
func configureViewForCurrentDocument() { guard let document = markdownDocument, !document.documentState.contains(.closed) && isViewLoaded else { return } // Configure views for document }
Customize navigation items
While UIDocumentViewController automatically sets the document title and other navigation items using information from the document, you can customize these items by overriding the navigationItemDidUpdate() method. The system calls navigationItemDidUpdate() every time UIDocumentViewController makes changes to the navigation item.
override func navigationItemDidUpdate() { // Customize the navigation item. }
Add sharing, drag and drop, and undo and redo
UIDocumentViewController automatically includes drag and drop, undo and redo, and sharing support. If you want undo and redo buttons to appear in your UIDocumentViewController, add a undoRedoItemGroup to the navigation bar and ensure that your custom UIDocument implements an undo manager. UIDocumentViewController sets the hidden property of this group, depending on the availability of an undo manager. It automatically enables or disables the buttons inside the group, as necessary.
Open a document from outside the class
UIDocumentViewController automatically opens and closes its document. However, if you need to access a document from outside the document view controller, you can create a new instance of UIDocumentViewController and call its openDocument(completionHandler:) method.
In this sample code, a UIDocumentBrowserViewController presents a document using a UIDocumentViewController.
// Open a document.
class BrowserViewController: UIDocumentBrowserViewController {
func presentDocument(_ document: MarkdownDocument) { let documentController = UIDocumentViewController(document: document) documentController.openDocument { success in if success { self.present(documentController, animated: true) } } }
}
UIDocumentViewController makes all the necessary callbacks, such as calling documentDidOpen() and, when the document is open, it calls the completion handler you provided.
Use the class as a root view controller
To use a UIDocumentViewController as the root view controller in an app, you need to declare the key “UIDocumentClass” for the relevant file type in your app’s info.plist. Set the document class to the UIDocument subclass you are using in your app.
If there is no browser view controller in the hierarchy, UIDocumentViewController displays a document button that opens a document picker in the navigation bar.
Topics
Creating a document view controller
init(document: UIDocument?)
Creates a document view controller with a document.
Managing the document view
var document: UIDocument?
The document that the controller presents or edits.
Opens a document in a document view controller from outside the document view controller.
func documentDidOpen()
Provides an opportunity to configure the view after the system loads the controller’s document into memory.
Customizing navigation items
func navigationItemDidUpdate()
Provides an opportunity to customize the navigation items after the navigation bar updates.
Adding undo and redo functionality
var undoRedoItemGroup: UIBarButtonItemGroup
The group that contains the undo/redo buttons that this view controller adds to the navigation bar.
Customizing the launch experience
var launchOptions: UIDocumentViewController.LaunchOptions
Options that customize a document-based app’s launch view.
class LaunchOptions
Options for customizing the document launch view.
Relationships
Inherits From
UIViewController
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSExtensionRequestHandlingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIActivityItemsConfigurationProvidingUIAppearanceContainerUIContentContainerUIFocusEnvironmentUIPasteConfigurationSupportingUIResponderStandardEditActionsUIStateRestoringUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
https://developer.apple.com/documentation/uikit/uidatasourcemodelassociation
https://developer.apple.com/documentation/uikit/uipastecontrol
- UIKit
- UIPasteControl
Class
UIPasteControl
A button that a person taps to place pasteboard contents in your app.
@MainActor class UIPasteControl
Overview
You can configure the button to appear as an icon, text, or both. The following button represents the icon and text option:
In iOS 16 and later, programmatic pasting raises a user alert that prompts the user for approval before the app gains access to pasteboard contents ( UIPasteboard.general.string). Use this class to paste without a user prompt.
Add a paste button to a text view
The following code displays a paste button and assigns a text view as the recipient of pasteboard contents:
let textView = UITextView(frame: view.bounds) view.addSubview(textView)
let configuration = UIPasteControl.Configuration() configuration.baseBackgroundColor = .red configuration.baseForegroundColor = .magenta configuration.cornerStyle = .capsule configuration.displayMode = .iconAndLabel
let pasteButton = UIPasteControl(configuration: configuration) pasteButton.frame = CGRect(x: view.bounds.width/2.0, y: view.bounds.height/2.0, width: 150, height: 60) textView.addSubview(pasteButton)
pasteButton.target = textView
Topics
Creating a paste button
init?(coder: NSCoder)
Creates a paste button by deserializing the specified coder.
init(configuration: UIPasteControl.Configuration)
Creates a paste button that conforms to the specified configuration.
init(frame: CGRect)
Creates a paste button with the specified size and position.
Identifying the content recipient
var target: (any UIPasteConfigurationSupporting)?
The UI control that receives pasted content.
Determining the button’s look
var configuration: UIPasteControl.Configuration
An object that customizes the look of the paste button.
class Configuration
An object that determines a paste button’s color, corner style, icon, and text.
Relationships
Inherits From
UIControl
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUIContextMenuInteractionDelegateUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Pasteboard
enum DisplayMode
Options that determine whether a paste button composes an icon, textual label, or both.
class UIPasteboard
An object that helps a user share data from one place to another within your app, and from your app to other apps.
class UIPasteConfiguration
The interface that an object implements to declare its ability to accept specific data types for pasting and for drag-and-drop activities.
protocol UIPasteConfigurationSupporting
The interface that determines whether a responder object supports paste configuration.
https://developer.apple.com/documentation/uikit/uipastecontrol/configuration-swift.class
- UIKit
- UIPasteControl
- UIPasteControl.Configuration
Class
UIPasteControl.Configuration
An object that determines a paste button’s color, corner style, icon, and text.
@MainActor class Configuration
Overview
The paste button ( UIPasteControl) property configuration is of this type.
Topics
Coloring the button
var baseBackgroundColor: UIColor?
A color for the paste button’s background.
var baseForegroundColor: UIColor?
A color for the paste button’s icon and text.
Shaping button corners
var cornerRadius: CGFloat
A value that rounds the edges of a paste button.
var cornerStyle: UIButton.Configuration.CornerStyle
A shape for the button among a predetermined set of templates.
Choosing control icon and text
var displayMode: UIPasteControl.DisplayMode
An option that determines whether the paste button composes an icon, textual label, or both.
enum DisplayMode
Options that determine whether a paste button composes an icon, textual label, or both.
Instance Properties
var imagePlacement: NSDirectionalRectEdge
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSSecureCodingSendable
See Also
Pasteboard
class UIPasteControl
A button that a person taps to place pasteboard contents in your app.
class UIPasteboard
An object that helps a user share data from one place to another within your app, and from your app to other apps.
class UIPasteConfiguration
The interface that an object implements to declare its ability to accept specific data types for pasting and for drag-and-drop activities.
protocol UIPasteConfigurationSupporting
The interface that determines whether a responder object supports paste configuration.
https://developer.apple.com/documentation/uikit/uipastecontrol/displaymode
- UIKit
- UIPasteControl
- UIPasteControl.DisplayMode
Enumeration
UIPasteControl.DisplayMode
Options that determine whether a paste button composes an icon, textual label, or both.
enum DisplayMode
Overview
The paste button ( UIPasteControl) property displayMode is of this type.
Topics
Choosing a display mode
case iconAndLabel
A display mode for a button that composes an icon and a textual label.
case iconOnly
A display mode for an icon button.
case labelOnly
A display mode for a textual label.
Enumeration Cases
case arrowAndLabel
Initializers
init?(rawValue: UInt)
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Pasteboard
class UIPasteControl
A button that a person taps to place pasteboard contents in your app.
class Configuration
An object that determines a paste button’s color, corner style, icon, and text.
class UIPasteboard
An object that helps a user share data from one place to another within your app, and from your app to other apps.
class UIPasteConfiguration
The interface that an object implements to declare its ability to accept specific data types for pasting and for drag-and-drop activities.
protocol UIPasteConfigurationSupporting
The interface that determines whether a responder object supports paste configuration.
https://developer.apple.com/documentation/uikit/uipasteboard
- UIKit
- UIPasteboard
Class
UIPasteboard
An object that helps a user share data from one place to another within your app, and from your app to other apps.
class UIPasteboard
Overview
For sharing data with any other app, use the systemwide general pasteboard. For sharing data with another app from your team — that has the same team ID as the app to share from — configure an App Group. For more information about configuring an App Group, see Configuring app groups.
In typical usage, an object in your app writes data to a pasteboard when the user requests a copy, cut, or duplicate operation on a selection in the user interface. Another object in the same or different app then reads that data from the pasteboard and presents it to the user at a new location. This usually happens when the user requests a paste operation.
The general pasteboard and named pasteboards
The system identifies the systemwide general pasteboard with the general pasteboard name, and you can use it for any type of data. Obtain the general pasteboard from the general shared system pasteboard object.
You can create named pasteboards with the class methods init(name:create:) and withUniqueName() for sharing data within your app, and from your app to other apps that have the same Team ID.
Using pasteboards
The UIPasteboard class provides methods for reading and writing individual pasteboard items, as well as methods for reading and writing multiple pasteboard items at once. For more information, see Getting and setting pasteboard items in the topic groups below. The data to write to a pasteboard can be in one of the following forms:
-
If the data is an object that conforms to
NSItemProviderWriting, usesetItemProviders(_:localOnly:expirationDate:)to write it to the pasteboard. -
If you can represent the data with a common object — such as
NSString,NSArray,NSDictionary,NSDate,NSNumber,UIImage, orNSURL— you can write it to the pasteboard as a value using a method such assetValue(_:forPasteboardType:). -
If the data is binary, use the
setData(_:forPasteboardType:)method to write it to the pasteboard.
The UIPasteboard class provides convenience methods for writing and reading strings, images, URLs, and colors to and from single or multiple pasteboard items. See Getting and setting pasteboard items of standard data types in the topic groups below.
UIPasteboard provides properties for directly checking whether specific data types are present on a pasteboard, see Checking for data types on a pasteboard in the topic groups below. Use these properties, rather than attempting to read pasteboard data, to avoid causing the system to needlessly attempt to fetch data before necessary, or when the data might not be present. For example, use the hasStrings property to determine whether to present a string-data paste option in the user interface, using code like the following:
if UIPasteboard.general.hasStrings { // Enable string-related control... }
Use the following properties to avoid user notifications and alerts when the system doesn’t establish user intent:
-
numberOfItems -
types,types(forItemSet:) -
itemSet(withPasteboardTypes:) -
hasColors,hasImages,hasStrings,hasURLs -
canLoadObject(ofClass:),canLoadObject(ofClass:) -
any of the pattern-detection methods in the Detecting patterns of content in pasteboard items group in the topic groups below
The system notifies the user when you access properties or call methods that pull data from the pasteboard if the system doesn’t determine that the user intends to access that data.
Pasteboard items and representation types
When you write an object to a pasteboard, the pasteboard stores it as a pasteboard item. A pasteboard item consists of one or more key-value pairs in which the key identifies the representation type (sometimes called a pasteboard type) of the value.
A uniform type identifier frequently functions as the key for a representation type. For example, you can use the UTTypeJPEG uniform type identifier (a constant for public.jpeg) as a representation type key for JPEG data.
For a discussion of uniform type identifiers, and a list of common ones, see Uniform Type Identifiers.
Your app can use any string to name a representation type; however, for app-specific data types, it’s best practice to use reverse-DNS notation to ensure the uniqueness of the type (for example, com.myCompany.myApp.myType).
You can provide flexibility for data sharing by providing multiple representation types for a pasteboard item during a copy or cut operation. Various contexts within your app or other apps can then make use of an appropriate representation type. For example, when a user copies an image, your app can write multiple representation types, such as in the PNG, JPEG, and GIF data formats, to a pasteboard. If the original image is in PNG format, but the receiving app can handle only GIF images, it can still use the pasteboard data.
For more about representation types, read the discussion for the types instance method.
Sharing pasteboards between devices
When a user signs into iCloud, the general pasteboard automatically transfers its contents to nearby devices that use the same iCloud account. You can control Handoff behavior when writing contents to the general pasteboard, and can set an expiration for items, using the setItemProviders(_:localOnly:expirationDate:), setObjects(_:localOnly:expirationDate:), or setItems(_:options:) methods, as follows:
-
To exclude a pasteboard from Handoff, specify
falsefor thelocalOnlyparameter, or call thesetItems(_:options:)method with thelocalOnlyoption. -
To indicate an expiration time and date for copied data, provide the
expirationDateparameter, or call thesetItems(_:options:)method with theexpirationDateoption. At the time and date that you set, the system removes the pasteboard items from the pasteboard.
Using pasteboards with other objects
Although the UIPasteboard class is central to copy, paste, and duplicate operations, you can employ protocols and instances of other UIKit classes in these operations as well, such as the following:
-
UIEditMenuInteraction— Displays a menu with edit actions, such as Copy, Cut, Paste, Select, and Select All, above or below the selection. -
UIActivityItemsConfigurationReading— Objects implement this protocol to indicate that they support copying and sharing data. -
UIPasteConfigurationSupporting— Objects implement this protocol to indicate whether they support pasting with a specificUIPasteConfiguration. -
UIResponder— Responders implementcanPerformAction(_:withSender:)to enable or disable commands in the above-mentioned menu based on the current context. -
UIResponderStandardEditActions— Responders implement methods that this informal protocol declares to handle the chosen menu commands (for example,copy:andpaste:).
A typical app that implements copy, paste, and duplicate operations also manages and presents related selections in its user interface. In addition, your app needs to coordinate changes in pasteboard content with changes to its data model, as appropriate for your app.
Topics
Getting and removing pasteboards
class var general: UIPasteboard
The systemwide general pasteboard, which you use for general copy-paste operations.
init?(name: UIPasteboard.Name, create: Bool)
Returns a pasteboard that you identify by name, optionally creating it if it doesn’t exist.
Returns an app pasteboard that you identify by a unique system-generated name.
class func remove(withName: UIPasteboard.Name)
Invalidates the designated app pasteboard.
Getting and setting pasteboard attributes
var name: UIPasteboard.Name
The name of the pasteboard.
var changeCount: Int
The number of times the pasteboard’s contents change.
Detecting patterns of content in pasteboard items
func detectPatterns(for: Set<PartialKeyPath<UIPasteboard.DetectedValues>>, completionHandler: (Result<Set<PartialKeyPath<UIPasteboard.DetectedValues>>, any Error>) -> ())
Requests that the data detection system identify the patterns that you specify for the pasteboard, and provide the patterns that it matches to your closure.
func detectedPatterns(for: Set<PartialKeyPath<UIPasteboard.DetectedValues>>) async throws -> Set<PartialKeyPath<UIPasteboard.DetectedValues>>
Requests that the data detection system asynchronously identify the patterns that you specify for the pasteboard, and return the patterns that it matches.
Requests that the data detection system identify the patterns that you specify for the pasteboard items, and provide the patterns that it matches to your closure.
Requests that the data detection system asynchronously identify the patterns that you specify for the pasteboard items, and return the patterns that it matches.
func detectValues(for: Set<PartialKeyPath<UIPasteboard.DetectedValues>>, completionHandler: (Result<UIPasteboard.DetectedValues, any Error>) -> ())
Requests that the data detection system identify the types of data that you specify for the pasteboard, and provide the values that it matches to your closure.
func detectedValues(for: Set<PartialKeyPath<UIPasteboard.DetectedValues>>) async throws -> UIPasteboard.DetectedValues
Requests that the data detection system asynchronously identify the types of values that you specify for the pasteboard, and return the values that it matches.
Requests that the data detection system identify the types of data that you specify for the pasteboard items, and provide the values that it matches to your closure.
Requests that the data detection system asynchronously identify the types of values that you specify for the pasteboard item, and return the values that it matches for each pasteboard.
struct DetectedValues
An object that contains common types of data that the data detection system matches for a pasteboard.
struct DetectionPattern
An object that represents a pattern to detect for the pasteboard, such as a URL, text, or a number.
Determining types of pasteboard items
The types of the first item on the pasteboard.
Returns an array of representation types for each specified pasteboard item.
Returns whether the pasteboard holds data of the specified representation type.
Returns whether the specified pasteboard items contain data of the given representation types.
Returns an index set identifying pasteboard items having the specified representation types.
Getting and setting pasteboard items
var numberOfItems: Int
The number of items for the pasteboard.
The pasteboard items on the pasteboard.
func addItems([[String : Any]])
Appends pasteboard items to the current contents of the pasteboard.
func setItems([[String : Any]], options: [UIPasteboard.OptionsKey : Any])
Adds an array of items to a pasteboard, and sets privacy options for all the items on the pasteboard.
Returns the data on the pasteboard for the given representation type.
Returns the data objects in the indicated pasteboard items that have the given representation type.
func setData(Data, forPasteboardType: String)
Puts data on the pasteboard for the specified representation type.
Returns an object on the pasteboard for the given representation type.
Returns the objects on the indicated pasteboard items that have the given representation type.
func setValue(Any, forPasteboardType: String)
Puts an object on the pasteboard for the specified representation type.
Getting and setting pasteboard items of standard data types
var string: String?
The string value of the first pasteboard item.
An array of strings in all pasteboard items.
var image: UIImage?
The image object of the first pasteboard item.
An array of image objects in all pasteboard items.
var url: URL?
The URL object of the first pasteboard item.
An array of URL objects in all pasteboard items.
var color: UIColor?
The color object of the first pasteboard item.
An array of color objects in all pasteboard items.
Checking for data types on a pasteboard
var hasColors: Bool
A Boolean value that indicates whether the pasteboard contains contains a nonempty array of colors.
var hasImages: Bool
A Boolean value that indicates whether the pasteboard contains a nonempty array of images.
var hasStrings: Bool
A Boolean value that indicates whether the pasteboard contains a nonempty array of strings.
var hasURLs: Bool
A Boolean value that indicates whether the pasteboard contains a nonempty array of URLs.
Getting and setting item providers
var itemProviders: [NSItemProvider]
An array of item providers for the pasteboard.
func setItemProviders([NSItemProvider], localOnly: Bool, expirationDate: Date?)
Sets and configures an explicit array of item providers for the pasteboard.
func setObjects([any NSItemProviderWriting])
Sets an array of item providers for the pasteboard, based on a specified array of objects.
func setObjects([any NSItemProviderWriting], localOnly: Bool, expirationDate: Date?)
Sets and configures an array of item providers for the pasteboard, based on a specified array of objects.
Constants
struct Name
Constants that identify the name of a pasteboard.
Names identifying the system pasteboards.
struct OptionsKey
Options for describing pasteboard privacy.
Pasteboard-item representation types, as for a given object value.
Use these keys to access the representation types of pasteboard items that you add to, or remove from, a pasteboard.
Notifications
class let changedNotification: NSNotification.Name
A notification that a pasteboard object posts when its contents change.
class let removedNotification: NSNotification.Name
A notification that a pasteboard object posts just before an app removes it.
Deprecated
Review unsupported symbols and their replacements.
Structures
struct ChangedMessage Beta
struct RemovedMessage Beta
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendableSendableMetatype
See Also
Pasteboard
class UIPasteControl
A button that a person taps to place pasteboard contents in your app.
class Configuration
An object that determines a paste button’s color, corner style, icon, and text.
enum DisplayMode
Options that determine whether a paste button composes an icon, textual label, or both.
class UIPasteConfiguration
The interface that an object implements to declare its ability to accept specific data types for pasting and for drag-and-drop activities.
protocol UIPasteConfigurationSupporting
The interface that determines whether a responder object supports paste configuration.
https://developer.apple.com/documentation/uikit/uipasteconfiguration
- UIKit
- UIPasteConfiguration
Class
UIPasteConfiguration
The interface that an object implements to declare its ability to accept specific data types for pasting and for drag-and-drop activities.
@MainActor class UIPasteConfiguration
Topics
Initializing a paste configuration
init()
Initializes a new paste configuration.
convenience init(acceptableTypeIdentifiers: [String])
Initializes a new paste configuration with a specified array of acceptable UTIs.
convenience init(forAccepting: any NSItemProviderReading.Type)
Initializes a new paste configuration with the UTIs declared as supported by a specified class.
Getting acceptable type identifiers
var acceptableTypeIdentifiers: [String]
An array of UTI strings that specify the types accepted by the paste configuration.
Adding acceptable type identifiers
func addAcceptableTypeIdentifiers([String])
Adds an array of UTI strings to a paste configuration, increasing the variety of types the paste configuration accepts.
func addTypeIdentifiers(forAccepting: any NSItemProviderReading.Type)
Expands the array of accepted UTIs for a paste configuration, based on those declared as supported by a specified class.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSCopyingNSObjectProtocolNSSecureCodingSendable
See Also
Pasteboard
class UIPasteControl
A button that a person taps to place pasteboard contents in your app.
class Configuration
An object that determines a paste button’s color, corner style, icon, and text.
enum DisplayMode
Options that determine whether a paste button composes an icon, textual label, or both.
class UIPasteboard
An object that helps a user share data from one place to another within your app, and from your app to other apps.
protocol UIPasteConfigurationSupporting
The interface that determines whether a responder object supports paste configuration.
https://developer.apple.com/documentation/uikit/uipasteconfigurationsupporting
- UIKit
- UIPasteConfigurationSupporting
Protocol
UIPasteConfigurationSupporting
The interface that determines whether a responder object supports paste configuration.
@MainActor protocol UIPasteConfigurationSupporting : NSObjectProtocol
Topics
Accessing the paste configuration
var pasteConfiguration: UIPasteConfiguration?
The paste configuration associated with the responder object.
Required
Performing a paste operation
Returns a Boolean value that determines whether the responder object can perform a paste operation using data provided by the item providers.
func paste(itemProviders: [NSItemProvider])
Performs a paste operation on the responder object.
Relationships
Inherits From
NSObjectProtocol
Inherited By
UITextDroppableUITextPasteConfigurationSupporting
Conforming Types
UIAccessibilityElementUIActionSheetUIActivityIndicatorViewUIActivityViewControllerUIAlertControllerUIAlertViewUIApplicationUIBackgroundExtensionViewUIButtonUICalendarViewUICloudSharingControllerUICollectionReusableViewUICollectionViewUICollectionViewCellUICollectionViewControllerUICollectionViewListCellUIColorPickerViewControllerUIColorWellUIContentUnavailableViewUIControlUIDatePickerUIDocumentBrowserViewControllerUIDocumentMenuViewControllerUIDocumentPickerExtensionViewControllerUIDocumentPickerViewControllerUIDocumentViewControllerUIEventAttributionViewUIFontPickerViewControllerUIImagePickerControllerUIImageViewUIInputViewUIInputViewControllerUILabelUIListContentViewUINavigationBarUINavigationControllerUIPageControlUIPageViewControllerUIPasteControlUIPickerViewUIPopoverBackgroundViewUIProgressViewUIReferenceLibraryViewControllerUIRefreshControlUIResponderUISceneUIScrollViewUISearchBarUISearchContainerViewControllerUISearchControllerUISearchTextFieldUISegmentedControlUISliderUISplitViewControllerUIStackViewUIStandardTextCursorViewUIStepperUISwitchUITabBarUITabBarControllerUITableViewUITableViewCellUITableViewControllerUITableViewHeaderFooterViewUITextFieldUITextFormattingViewControllerUITextViewUIToolbarUIVideoEditorControllerUIViewUIViewControllerUIVisualEffectViewUIWebViewUIWindowUIWindowScene
See Also
Pasteboard
class UIPasteControl
A button that a person taps to place pasteboard contents in your app.
class Configuration
An object that determines a paste button’s color, corner style, icon, and text.
enum DisplayMode
Options that determine whether a paste button composes an icon, textual label, or both.
class UIPasteboard
An object that helps a user share data from one place to another within your app, and from your app to other apps.
class UIPasteConfiguration
The interface that an object implements to declare its ability to accept specific data types for pasting and for drag-and-drop activities.
https://developer.apple.com/documentation/uikit/uimanageddocument)
https://developer.apple.com/documentation/uikit/synchronizing-documents-in-the-icloud-environment)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocumentviewcontroller)
https://developer.apple.com/documentation/uikit/uidatasourcemodelassociation)
https://developer.apple.com/documentation/uikit/uipastecontrol)
https://developer.apple.com/documentation/uikit/uipastecontrol/configuration-swift.class)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uipastecontrol/displaymode)
https://developer.apple.com/documentation/uikit/uipasteboard)
https://developer.apple.com/documentation/uikit/uipasteconfiguration)
https://developer.apple.com/documentation/uikit/uipasteconfigurationsupporting)
https://developer.apple.com/documentation/uikit/uiactionsheet
- UIKit
- UIActionSheet Deprecated
Class
UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
iOS 2.0–8.3DeprecatediPadOS 2.0–8.3DeprecatedMac Catalyst 13.1–13.1Deprecated
@MainActor class UIActionSheet
Overview
In apps that target versions of iOS prior to iOS 8, use the UIActionSheet class to present the user with a set of alternatives for how to proceed with a given task. You can also use action sheets to prompt the user to confirm a potentially dangerous action. The action sheet contains an optional title and one or more buttons, each of which corresponds to an action to take.
Use the properties and methods of this class to configure the action sheet’s message, style, and buttons before presenting it. You should also assign a delegate to your action sheet. Your delegate object is responsible for performing the action associated with any buttons when they’re tapped and should conform to the UIActionSheetDelegate protocol. For more information about implementing the methods of the delegate, see UIActionSheetDelegate.
You can present an action sheet from a toolbar, tab bar, button bar item, or from a view. This class takes the starting view and current platform into account when determining how to present the action sheet. For applications running on iPhone and iPod touch devices, the action sheet typically slides up from the bottom of the window that owns the view. For applications running on iPad devices, the action sheet is typically displayed in a popover that’s anchored to the starting view in an appropriate way. Taps outside of the popover automatically dismiss the action sheet, as do taps within any custom buttons. You can also dismiss it programmatically.
When presenting an action sheet on an iPad, there are times when you shouldn’t include a cancel button. If you’re presenting just the action sheet, the system displays the action sheet inside a popover without using an animation. Because taps outside the popover dismiss the action sheet without selecting an item, this results in a default way to cancel the sheet. Including a cancel button would therefore only cause confusion. However, if you have an existing popover and are displaying an action sheet on top of other content using an animation, a cancel button is still appropriate. For more information, see iOS Human Interface Guidelines.
Subclassing notes
UIActionSheet isn’t designed to be subclassed, nor should you add views to its hierarchy. If you need to present a sheet with more customization than provided by the UIActionSheet API, you can create your own and present it modally with present(_:animated:completion:).
Topics
Creating action sheets
convenience init(title: String?, delegate: (any UIActionSheetDelegate)?, cancelButtonTitle: String?, destructiveButtonTitle: String?, otherButtonTitles: String, String...)
Creates an action sheet with the specified values.
init(title: String?, delegate: (any UIActionSheetDelegate)?, cancelButtonTitle: String?, destructiveButtonTitle: String?)
Initializes the action sheet using the specified starting parameters.
Setting properties
var delegate: (any UIActionSheetDelegate)?
The receiver’s delegate or nil if it doesn’t have a delegate.
var title: String
The string that appears in the receiver’s title bar.
var isVisible: Bool
A Boolean value that indicates whether the receiver is displayed.
var actionSheetStyle: UIActionSheetStyle
The receiver’s presentation style.
Configuring buttons
Adds a custom button to the action sheet.
var numberOfButtons: Int
The number of buttons on the action sheet.
Returns the title of the button at the specified index.
var cancelButtonIndex: Int
The index number of the cancel button.
var destructiveButtonIndex: Int
The index number of the destructive button.
var firstOtherButtonIndex: Int
The index of the first custom button.
Presenting the action sheet
func show(from: UITabBar)
Displays an action sheet that originates from the specified tab bar.
func show(from: UIToolbar)
Displays an action sheet that originates from the specified toolbar.
func show(in: UIView)
Displays an action sheet that originates from the specified view.
func show(from: UIBarButtonItem, animated: Bool)
Displays an action sheet that originates from the specified bar button item.
func show(from: CGRect, in: UIView, animated: Bool)
Dismissing the action sheet
func dismiss(withClickedButtonIndex: Int, animated: Bool)
Dismisses the action sheet immediately using an optional animation.
Constants
enum UIActionSheetStyle
Specifies the style of an action sheet.
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Deprecated classes
class UIAlertView
A view that displays an alert message.
Deprecated
class UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
class UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
class UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
class UIMenuItem
A custom item in the editing menu managed by the menu controller.
class UIMutableUserNotificationAction
A modifiable version of the user notification action class.
class UIMutableUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
class UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
class UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
class UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
class UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
class UIUserNotificationCategory
class UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
https://developer.apple.com/documentation/uikit/uialertview
- UIKit
- UIAlertView Deprecated
Class
UIAlertView
A view that displays an alert message.
iOS 2.0–9.0DeprecatediPadOS 2.0–9.0DeprecatedMac Catalyst 13.1–13.1Deprecated
@MainActor class UIAlertView
Overview
In apps that run in versions of iOS prior to iOS 8, use the UIAlertView class to display an alert message to the user. An alert view functions similar to but differs in appearance from an action sheet (an instance of UIActionSheet).
Using an alert view
Use the properties and methods defined in this class to set the title, message, and delegate of an alert view and configure the buttons in apps that run in versions of iOS prior to iOS 8. You must set a delegate if you add custom buttons. The delegate should conform to the UIAlertViewDelegate protocol. Use the show() method to display an alert view after it’s configured.
Subclassing notes
The UIAlertView class is intended to be used as-is and doesn’t support subclassing. The view hierarchy for this class is private and must not be modified.
Topics
Creating alert views
convenience init(title: String?, message: String?, delegate: Any?, cancelButtonTitle: String?)
Convenience method for initializing an alert view.
convenience init(title: String, message: String, delegate: (any UIAlertViewDelegate)?, cancelButtonTitle: String?, otherButtonTitles: String, String...)
Creates an alert view with the specified values.
init(frame: CGRect)
Creates an alert view with the specified frame.
init?(coder: NSCoder)
Creates an alert view from data in an unarchiver.
Setting properties
var delegate: AnyObject?
The receiver’s delegate or nil if it doesn’t have a delegate.
var alertViewStyle: UIAlertViewStyle
The kind of alert displayed to the user.
var title: String
The string that appears in the receiver’s title bar.
var message: String?
Descriptive text that provides more details than the title.
var isVisible: Bool
A Boolean value that indicates whether the receiver is displayed.
Configuring buttons
Adds a button to the receiver with the given title.
var numberOfButtons: Int
The number of buttons on the alert view.
Returns the title of the button at the given index.
Returns the text field at the given index
var cancelButtonIndex: Int
The index number of the cancel button.
var firstOtherButtonIndex: Int
The index of the first other button.
Displaying
func show()
Displays the receiver using animation.
Dismissing
func dismiss(withClickedButtonIndex: Int, animated: Bool)
Dismisses the receiver, optionally with animation.
Constants
enum UIAlertViewStyle
The presentation style of the alert.
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Deprecated classes
class UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
Deprecated
class UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
class UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
class UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
class UIMenuItem
A custom item in the editing menu managed by the menu controller.
class UIMutableUserNotificationAction
A modifiable version of the user notification action class.
class UIMutableUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
class UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
class UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
class UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
class UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
class UIUserNotificationCategory
class UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
https://developer.apple.com/documentation/uikit/uidocumentmenuviewcontroller
- UIKit
- UIDocumentMenuViewController Deprecated
Class
UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
iOS 8.0–11.0DeprecatediPadOS 8.0–11.0DeprecatedMac Catalyst 13.1–13.1Deprecated
@MainActor class UIDocumentMenuViewController
Topics
Creating a document menu
init(documentTypes: [String], in: UIDocumentPickerMode)
Initializes and returns a document menu to import or open the given file types.
init(url: URL, in: UIDocumentPickerMode)
Initializes and returns a document menu to export or move the given document.
init?(coder: NSCoder)
Creates a document menu from data in an unarchiver.
Getting the user-selected document picker
var delegate: (any UIDocumentMenuDelegate)?
The document menu’s delegate.
protocol UIDocumentMenuDelegate
A set of methods that you must implement to track user interactions with a document menu view controller.
Configuring a document menu
Adds a custom menu item to the list of document pickers.
enum UIDocumentMenuOrder
The insertion point for custom menu items.
Relationships
Inherits From
UIViewController
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSExtensionRequestHandlingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIActivityItemsConfigurationProvidingUIAppearanceContainerUIContentContainerUIFocusEnvironmentUIPasteConfigurationSupportingUIResponderStandardEditActionsUIStateRestoringUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Deprecated classes
class UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
Deprecated
class UIAlertView
A view that displays an alert message.
class UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
class UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
class UIMenuItem
A custom item in the editing menu managed by the menu controller.
class UIMutableUserNotificationAction
A modifiable version of the user notification action class.
class UIMutableUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
class UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
class UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
class UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
class UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
class UIUserNotificationCategory
class UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
https://developer.apple.com/documentation/uikit/uilocalnotification
- UIKit
- UILocalNotification Deprecated
Class
UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
iOS 4.0–10.0DeprecatediPadOS 4.0–10.0DeprecatedMac Catalyst 13.1–13.1DeprecatedwatchOS 2.0–3.0Deprecated
@MainActor class UILocalNotification
Overview
The operating system is responsible for delivering local notifications at their scheduled times; the app does not have to be running for this to happen. Although local notifications are similar to remote notifications in that they are used for displaying alerts, playing sounds, and badging app icons, they are composed and delivered locally and do not require connection with remote servers.
Local notifications are primarily intended for apps with timer-based behaviors and simple calendar or to-do list apps. An app that is running in the background may also schedule a local notification to inform the user of an incoming message, chat, or update. An app can have only a limited number of scheduled notifications; the system keeps the soonest-firing 64 notifications (with automatically rescheduled notifications counting as a single notification) and discards the rest.
When you create a local notification, you must specify either a specific date or a geographic region as the trigger for delivering the notification. Date-based notifications are delivered at the day and time you specify, and allowances can be made for time zone changes as needed. Region-based notifications are delivered when the user enters or exits the specified region. In both cases, you can specify whether the notifications are one-time events or can be rescheduled and delivered again.
After creating a UILocalNotification object, schedule it using either the scheduleLocalNotification(_:) or presentLocalNotificationNow(_:) method of the UIApplication class. The scheduleLocalNotification(_:) method uses the fire date to schedule delivery; the presentLocalNotificationNow(_:) method presents the notification immediately, regardless of the value of fireDate. You can cancel one or more local notifications using the cancelLocalNotification(_:) or cancelAllLocalNotifications() method of the UIApplication object.
When the system delivers a local notification, several things can happen, depending on the app state and the type of notification. If the app is not frontmost and visible, the system displays the alert message, badges the app, and plays a sound—whatever is specified in the notification. If the notification is an alert and the user taps the action button (or, if the device is locked, drags open the action slider), the app is woken up or launched. (If the user taps one of the custom actions you specify using the category property, the app is woken up or launched into the background.) In its application(_:didFinishLaunchingWithOptions:) method, the app delegate can obtain the UILocalNotification object from the launch options dictionary using the localNotification key. The delegate can inspect the properties of the notification and, if the notification includes custom data in its userInfo dictionary, it can access that data and process it accordingly. On the other hand, if the local notification only badges the app icon, and the user in response launches the app, the application(_:didFinishLaunchingWithOptions:) method is called, but no UILocalNotification object is included in the options dictionary. When the user selects a custom action, the app delegate’s application(_:handleActionWithIdentifier:for:completionHandler:) method is called to handle the action.
If the app is foremost and visible when the system delivers the notification, the app delegate’s application(_:didReceive:) is called to process the notification. Use the information in the provided UILocalNotification object to decide what action to take. The system does not display any alerts, badge the app’s icon, or play any sounds when the app is already frontmost.
An app is responsible for managing the badge number displayed on its icon. For example, if a text-messaging app processes all incoming messages after receiving a local notification, it should remove the icon badge by setting the applicationIconBadgeNumber property of the UIApplication object to 0.
Topics
Scheduling a local notification
var fireDate: Date?
The date and time when the system should deliver the notification.
var timeZone: TimeZone?
The time zone of the notification’s fire date.
var repeatInterval: NSCalendar.Unit
The calendar interval at which to reschedule the notification.
var repeatCalendar: Calendar?
The calendar the system should refer to when it reschedules a repeating notification.
var region: CLRegion?
The geographic region that triggers the notification.
var regionTriggersOnce: Bool
A Boolean value indicating whether crossing a geographic region boundary delivers only one notification.
Composing the alert
var alertBody: String?
The message displayed in the notification alert.
var alertAction: String?
The title of the action button or slider.
var alertTitle: String?
A short description of the reason for the alert.
var hasAction: Bool
A Boolean value that controls whether the notification shows or hides the alert action.
var alertLaunchImage: String?
Identifies the image used as the launch image when the user taps (or slides) the action button (or slider).
var category: String?
The name of a group of actions to display in the alert.
Configuring other parts of the notification
var applicationIconBadgeNumber: Int
The number to display as the app’s icon badge.
var soundName: String?
The name of the file containing the sound to play when an alert is displayed.
var userInfo: [AnyHashable : Any]?
A dictionary for passing custom information to the notified app.
Constants
The default system sound for local notifications.
Initializers
init()
init?(coder: NSCoder)
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSCopyingNSObjectProtocolSendable
See Also
Deprecated classes
class UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
Deprecated
class UIAlertView
A view that displays an alert message.
class UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
class UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
class UIMenuItem
A custom item in the editing menu managed by the menu controller.
class UIMutableUserNotificationAction
A modifiable version of the user notification action class.
class UIMutableUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
class UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
class UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
class UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
class UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
class UIUserNotificationCategory
class UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
https://developer.apple.com/documentation/uikit/uimenucontroller
- UIKit
- UIMenuController Deprecated
Class
UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
iOS 3.0–16.0DeprecatediPadOS 3.0–16.0DeprecatedMac Catalyst 13.1–16.0DeprecatedvisionOS 1.0–1.0Deprecated
@MainActor class UIMenuController
Overview
The singleton UIMenuController instance is referred to as the editing menu. When you make this menu visible, UIMenuController positions it relative to a target rectangle on the screen; this rectangle usually defines a selection. The menu appears above the target rectangle or, if there isn’t enough space for it, below it. The menu’s pointer is placed at the center of the top or bottom of the target rectangle, as appropriate. Be sure to set the tracking rectangle before you make the menu visible. You’re also responsible for detecting, tracking, and displaying selections.
The UIResponderStandardEditActions informal protocol declares methods that are invoked when the user taps a menu command. The canPerformAction(_:withSender:) method of UIResponder is also related to the editing menu. A responder implements this method to enable and disable commands of the editing menu just before the menu is displayed. You can force the menu commands enabled state to update by calling the update() method.
You can also provide your own menu items via the menuItems property. When you modify the menu items, you can use the update() method to force the menu to update its display.
Topics
Getting the menu controller instance
class var shared: UIMenuController
Returns the menu controller.
Showing and hiding the menu
func showMenu(from: UIView, rect: CGRect)
func hideMenu(from: UIView)
func hideMenu()
var isMenuVisible: Bool
The visibility of the editing menu.
func setMenuVisible(Bool, animated: Bool)
Shows or hides the editing menu, optionally animating the action.
Positioning the menu
var menuFrame: CGRect
Returns the frame of the editing menu.
var arrowDirection: UIMenuController.ArrowDirection
The direction the arrow of the editing menu is pointing.
enum ArrowDirection
func setTargetRect(CGRect, in: UIView)
Sets the area in a view above or below which the editing menu is positioned.
Updating the menu
func update()
Updates the appearance and enabled state of menu commands.
Customizing menu items
The custom menu items for the editing menu.
Notifications
class let willShowMenuNotification: NSNotification.Name
Posted by the menu controller just before it shows the menu.
class let didShowMenuNotification: NSNotification.Name
Posted by the menu controller just after it shows the menu.
class let willHideMenuNotification: NSNotification.Name
Posted by the menu controller just before it hides the menu.
class let didHideMenuNotification: NSNotification.Name
Posted by the menu controller just after it hides the menu.
class let menuFrameDidChangeNotification: NSNotification.Name
Posted when the frame of a visible menu changes.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendable
See Also
Deprecated classes
class UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
Deprecated
class UIAlertView
A view that displays an alert message.
class UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
class UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
class UIMenuItem
A custom item in the editing menu managed by the menu controller.
class UIMutableUserNotificationAction
A modifiable version of the user notification action class.
class UIMutableUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
class UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
class UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
class UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
class UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
class UIUserNotificationCategory
class UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
https://developer.apple.com/documentation/uikit/uimenuitem
- UIKit
- UIMenuItem Deprecated
Class
UIMenuItem
A custom item in the editing menu managed by the menu controller.
iOS 3.2–16.0DeprecatediPadOS 3.2–16.0DeprecatedMac Catalyst 13.1–16.0DeprecatedvisionOS 1.0–1.0Deprecated
@MainActor class UIMenuItem
Overview
Custom menu items appear in the menu after any validated system items. A UIMenuItem object has two properties: a title and an action selector identifying the method to invoke in the handling responder object. Targets aren’t specified; a suitable target is found via normal traversal of the responder chain. To have custom menu items appear in the editing menu, you must add them to the menuItems property of the UIMenuController object.
Topics
Creating a menu item
init(title: String, action: Selector)
Creates and returns a menu-item object initialized with the given title and action.
Accessing menu-item attributes
var title: String
The title of the menu item.
var action: Selector
A selector identifying the method of the responder object to invoke for handling of the menu command.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendable
See Also
Deprecated classes
class UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
Deprecated
class UIAlertView
A view that displays an alert message.
class UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
class UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
class UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
class UIMutableUserNotificationAction
A modifiable version of the user notification action class.
class UIMutableUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
class UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
class UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
class UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
class UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
class UIUserNotificationCategory
class UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
https://developer.apple.com/documentation/uikit/uimutableusernotificationaction
- UIKit
- UIMutableUserNotificationAction Deprecated
Class
UIMutableUserNotificationAction
A modifiable version of the user notification action class.
iOS 8.0–10.0DeprecatediPadOS 8.0–10.0DeprecatedMac Catalyst 13.1–13.1Deprecated
@MainActor class UIMutableUserNotificationAction
Overview
When a notification is delivered, the system displays a button for each custom action associated with the notification. Tapping a button launches your app (either in the foreground or background) and gives you a chance to perform the indicated action. You use this class to configure the details about the button that is displayed and the information your app needs to perform the corresponding action.
To associate custom actions with a local or remote notification, create one or more instances of this class and use them to configure one or more UIMutableUserNotificationActionSettings objects. An action settings objects defines the set of actions to associate with a single notification. You register your app’s action settings objects at launch time, along with your app’s preferred notification options, using a UIUserNotificationSettings object.
For each action you define, you must specify whether execution of that action requires the app to be running in the foreground or background. You can also specify whether the device must be unlocked or can remain locked while the action is performed. Unlocking the device may be necessary if the action involves reading or writing files that are encrypted on disk using the system’s data protection mechanism. When the user selects an action, the system puts your app into the appropriate mode and calls your app delegate’s application(_:handleActionWithIdentifier:forRemoteNotification:completionHandler:) or application(_:handleActionWithIdentifier:for:completionHandler:) method to perform the action.
Topics
Getting the action information
var identifier: String?
The string that you use internally to identify the action.
var title: String?
The localized string to use as the button title for the action.
Configuring the action’s behavior
var activationMode: UIUserNotificationActivationMode
The mode in which to run the app when the action is performed.
var isAuthenticationRequired: Bool
A Boolean value indicating whether the user must unlock the device before the action is performed.
var isDestructive: Bool
A Boolean value indicating whether the action is destructive.
var behavior: UIUserNotificationActionBehavior
The custom behavior (if any) that the action supports.
var parameters: [AnyHashable : Any]
A dictionary of additional parameters to include with the action.
Relationships
Inherits From
UIUserNotificationAction
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSCopyingNSMutableCopyingNSObjectProtocolNSSecureCoding
See Also
Deprecated classes
class UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
Deprecated
class UIAlertView
A view that displays an alert message.
class UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
class UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
class UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
class UIMenuItem
A custom item in the editing menu managed by the menu controller.
class UIMutableUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
class UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
class UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
class UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
class UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
class UIUserNotificationCategory
class UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
https://developer.apple.com/documentation/uikit/uimutableusernotificationcategory
- UIKit
- UIMutableUserNotificationCategory Deprecated
Class
UIMutableUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
iOS 8.0–10.0DeprecatediPadOS 8.0–10.0DeprecatedMac Catalyst 13.1–13.1Deprecated
@MainActor class UIMutableUserNotificationCategory
Overview
Use instances of this class to customize the actions included in an alert when space onscreen is constrained.
After creating an instance of this class using the standard alloc/init pattern, use it to modify the actions or category name as needed. The most common use of this class is to specify the subset of actions to display when the size of the alert is relatively small.
Topics
Modifying the action settings
var identifier: String?
The name of the action group.
func setActions([UIUserNotificationAction]?, for: UIUserNotificationActionContext)
Sets the actions to display for different alert styles.
Relationships
Inherits From
UIUserNotificationCategory
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSCopyingNSMutableCopyingNSObjectProtocolNSSecureCoding
See Also
Deprecated classes
class UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
Deprecated
class UIAlertView
A view that displays an alert message.
class UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
class UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
class UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
class UIMenuItem
A custom item in the editing menu managed by the menu controller.
class UIMutableUserNotificationAction
A modifiable version of the user notification action class.
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
class UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
class UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
class UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
class UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
class UIUserNotificationCategory
class UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
https://developer.apple.com/documentation/uikit/uipopovercontroller
https://developer.apple.com/documentation/uikit/uipreviewaction
- UIKit
- UIPreviewAction Deprecated
Class
UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
iOS 9.0–13.0DeprecatediPadOS 9.0–13.0DeprecatedMac Catalyst 13.1–13.1DeprecatedtvOS 9.0–13.0Deprecated
@MainActor class UIPreviewAction
Overview
A peek quick action typically selects a deep link to your app and has a title, a style, and a handler. Peeks and peek quick actions are available on devices that support 3D Touch.
Topics
Creating a peek quick action
Creates a peek quick action using a specified title, style, and handler.
The block called when the peek quick action is selected by the user.
enum Style
The style for a peek quick action.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCopyingNSObjectProtocolSendableUIPreviewActionItem
See Also
Deprecated classes
class UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
Deprecated
class UIAlertView
A view that displays an alert message.
class UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
class UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
class UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
class UIMenuItem
A custom item in the editing menu managed by the menu controller.
class UIMutableUserNotificationAction
A modifiable version of the user notification action class.
class UIMutableUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
class UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
class UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
class UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
class UIUserNotificationCategory
class UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
https://developer.apple.com/documentation/uikit/uipreviewactiongroup
- UIKit
- UIPreviewActionGroup Deprecated
Class
UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
iOS 9.0–13.0DeprecatediPadOS 9.0–13.0DeprecatedMac Catalyst 13.1–13.1DeprecatedtvOS 9.0–13.0Deprecated
@MainActor class UIPreviewActionGroup
Overview
When first displayed, the group appears as a single option in a peek quick action sheet. If the user selects the group, a submenu opens, displaying the child quick actions.
Topics
Creating a peek quick action group
convenience init(title: String, style: UIPreviewAction.Style, actions: [UIPreviewAction])
Creates a peek quick action group using a specified title, style, and array of peek quick actions.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCopyingNSObjectProtocolSendableUIPreviewActionItem
See Also
Deprecated classes
class UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
Deprecated
class UIAlertView
A view that displays an alert message.
class UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
class UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
class UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
class UIMenuItem
A custom item in the editing menu managed by the menu controller.
class UIMutableUserNotificationAction
A modifiable version of the user notification action class.
class UIMutableUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
class UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
class UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
class UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
class UIUserNotificationCategory
class UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
https://developer.apple.com/documentation/uikit/uisearchdisplaycontroller
- UIKit
- UISearchDisplayController Deprecated
Class
UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
iOS 3.0–8.0DeprecatediPadOS 3.0–8.0DeprecatedMac Catalyst 13.1–13.1Deprecated
@MainActor class UISearchDisplayController
Overview
You initialize a search display controller with a search bar and a view controller responsible for managing the data to be searched. When the user starts a search, the search display controller superimposes the search interface over the original view controller’s view and shows the search results in its table view.
In addition to managing the searchable data, the original view controller typically plays four more roles you need to fill when using a search display controller. Those roles are the following:
-
Data source for the search results table view (
searchResultsDataSource), which provides the data for the results table. -
Delegate for the search results table view (
searchResultsDelegate), which responds to the user’s selection of an item in the results table. -
Delegate for the search display controller (
delegate), which responds to events such the starting or ending of a search, and the showing or hiding of the search interface. As a convenience, this delegate may also be told about changes to the search string or search scope, so that the results table view can be reloaded. -
Delegate for the search bar (
delegatedescribed inUISearchBar), which responds to changes in search criteria.
Typically, you initialize a search display controller from a view controller (usually an instance of UITableViewController) that’s displaying a list. See the Simple UISearchBar with State Restoration sample code project for an example of how to configure a search display controller in Interface Builder. To perform configuration programmatically, set self for the search display controller’s view controller and search results data source and delegate, as shown here:
searchController = [[UISearchDisplayController alloc]
initWithSearchBar:searchBar contentsController:self];
searchController.delegate = self;
searchController.searchResultsDataSource = self;
searchController.searchResultsDelegate = self;
If you follow this pattern, then in the table view data source and delegate methods you can check the methods’ table view argument to determine which table view is sending the message:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.tableView) { return ...; } // If necessary (if self is the data source for other table views), // check whether tableView is searchController.searchResultsTableView. return ...; }
Starting in iOS 7.0, you can use a search display controller with a navigation bar (an instance of the UINavigationBar class) by configuring the search display controller’s displaysSearchBarInNavigationBar and navigationItem properties.
Topics
Initializing a search bar
init(searchBar: UISearchBar, contentsController: UIViewController)
Returns a display controller initialized with the given search bar and contents controller.
Displaying the search Interface
var isActive: Bool
The visibility state of the search interface.
func setActive(Bool, animated: Bool)
Displays or hides the search interface, optionally with animation.
Configuring a search bar
var delegate: (any UISearchDisplayDelegate)?
The controller’s delegate.
var searchBar: UISearchBar
The search bar.
var searchContentsController: UIViewController
The view controller that manages the contents being searched.
var searchResultsTableView: UITableView
The table view in which the search results are displayed.
var searchResultsDataSource: (any UITableViewDataSource)?
The data source for the table view in which the search results are displayed.
var searchResultsDelegate: (any UITableViewDelegate)?
The delegate for the table view in which the search results are displayed.
var searchResultsTitle: String?
The title for the search results view.
var displaysSearchBarInNavigationBar: Bool
Specifies that the navigation bar contains a search bar.
var navigationItem: UINavigationItem?
Represents the search display controller in a navigation controller’s navigation bar.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendable
See Also
Deprecated classes
class UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
Deprecated
class UIAlertView
A view that displays an alert message.
class UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
class UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
class UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
class UIMenuItem
A custom item in the editing menu managed by the menu controller.
class UIMutableUserNotificationAction
A modifiable version of the user notification action class.
class UIMutableUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
class UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
class UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
class UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
class UIUserNotificationCategory
class UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
https://developer.apple.com/documentation/uikit/uistoryboardpopoversegue
- UIKit
- UIStoryboardPopoverSegue Deprecated
Class
UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
iOS 5.0–9.0DeprecatediPadOS 5.0–9.0DeprecatedMac Catalyst 13.1–13.1DeprecatedtvOSDeprecated
@MainActor class UIStoryboardPopoverSegue
Overview
For popover segues, the destination view controller contains the content to be displayed in the popover. This class provides an additional popoverController property so that your custom code has access to the popover controller object. For example, you might want to store the popover controller elsewhere in your code so that you can dismiss the popover programmatically.
Topics
Accessing the segue attributes
var popoverController: UIPopoverController
The popover controller used to display the destination view controller.
Relationships
Inherits From
UIStoryboardSegue
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendableSendableMetatype
See Also
Deprecated classes
class UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
Deprecated
class UIAlertView
A view that displays an alert message.
class UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
class UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
class UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
class UIMenuItem
A custom item in the editing menu managed by the menu controller.
class UIMutableUserNotificationAction
A modifiable version of the user notification action class.
class UIMutableUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
class UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
class UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
class UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
class UIUserNotificationCategory
class UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
https://developer.apple.com/documentation/uikit/uiusernotificationaction
- UIKit
- UIUserNotificationAction Deprecated
Class
UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
iOS 8.0–10.0DeprecatediPadOS 8.0–10.0DeprecatedMac Catalyst 13.1–13.1Deprecated
@MainActor class UIUserNotificationAction
Overview
When a notification is delivered, the system displays a button for each custom action associated with the notification. Tapping a button launches your app (either in the foreground or background) and gives you a chance to perform the indicated action. You use this class to specify the text that is displayed in the button and the information your app needs to perform the corresponding action.
Typically, you create an instance of the UIMutableUserNotificationAction class instead of this class. You use the mutable object to configure the action and then call the setActions:forContext: method of UIMutableUserNotificationActionSettings to add the resulting actions to a group.
For each action you define, you must specify whether execution of that action requires the app to be running in the foreground or background. You can also specify whether the device must be unlocked or can remain locked while the action is performed. Unlocking the device may be necessary if the action involves reading or writing files that are encrypted on disk using the system’s data protection mechanism. When the user selects an action, the system puts your app into the appropriate mode and calls your app delegate’s application(_:handleActionWithIdentifier:forRemoteNotification:completionHandler:) or application(_:handleActionWithIdentifier:for:completionHandler:) method to perform the action.
Topics
Creating the action
init()
Creates a user notification action.
init?(coder: NSCoder)
Creates a user notification action from data in an unarchiver.
Getting the action information
var identifier: String?
The string that you use internally to identify the action.
var title: String?
The localized string to use as the button title for the action.
Getting the action’s configuration
var activationMode: UIUserNotificationActivationMode
The mode in which to run the app when the action is performed.
var isAuthenticationRequired: Bool
A Boolean value indicating whether the user must unlock the device before the action is performed.
var isDestructive: Bool
A Boolean value indicating whether the action is destructive.
var behavior: UIUserNotificationActionBehavior
The custom behavior (if any) that the action supports.
var parameters: [AnyHashable : Any]
A dictionary of additional parameters to include with the action.
Constants
enum UIUserNotificationActivationMode
Constants indicating whether the app should activate to the foreground or background.
enum UIUserNotificationActionBehavior
Constants indicating additional behavior that the action supports.
Key to include among the parameters of the action.
Key related to action-related behaviors.
Relationships
Inherits From
NSObject
Inherited By
UIMutableUserNotificationAction
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSCopyingNSMutableCopyingNSObjectProtocolNSSecureCodingSendable
See Also
Deprecated classes
class UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
Deprecated
class UIAlertView
A view that displays an alert message.
class UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
class UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
class UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
class UIMenuItem
A custom item in the editing menu managed by the menu controller.
class UIMutableUserNotificationAction
A modifiable version of the user notification action class.
class UIMutableUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
class UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
class UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
class UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
class UIUserNotificationCategory
class UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
https://developer.apple.com/documentation/uikit/uiusernotificationcategory
- UIKit
- UIUserNotificationCategory Deprecated
Class
UIUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
iOS 8.0–10.0DeprecatediPadOS 8.0–10.0DeprecatedMac Catalyst 13.1–13.1Deprecated
@MainActor class UIUserNotificationCategory
Overview
Each instance of UIUserNotificationCategory represents a group of actions to display in conjunction with a single notification. The title of each action is uses as the title of a button in the alert displayed to the user. When the user taps a button, the system reports the selected action to your app delegate.
Typically, you create an instance of the UIMutableUserNotificationCategory class instead of this class. You use the mutable object to add actions and specify a category name before registering them with a UIUserNotificationSettings object.
To display a group of actions for a specific notification, configure the local or push notification with the category name of the group. For local notifications, you specify this name when configuring your UILocalNotification object. For push notifications, your server specifies a group of actions by adding a category key (whose value is the identifier of the group) to the push notification’s payload.
Topics
Creating the action group
init()
Creates an action group.
init?(coder: NSCoder)
Creates an action group from data in an unarchiver.
Getting the group configuration
var identifier: String?
The name of the action group.
Returns the actions to be displayed for the given notification context.
Constants
enum UIUserNotificationActionContext
Constants indicating the amount of space available for displaying actions in a notification.
Relationships
Inherits From
NSObject
Inherited By
UIMutableUserNotificationCategory
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSCopyingNSMutableCopyingNSObjectProtocolNSSecureCodingSendable
See Also
Deprecated classes
class UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
Deprecated
class UIAlertView
A view that displays an alert message.
class UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
class UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
class UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
class UIMenuItem
A custom item in the editing menu managed by the menu controller.
class UIMutableUserNotificationAction
A modifiable version of the user notification action class.
class UIMutableUserNotificationCategory
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
class UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
class UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
class UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
class UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
class UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
https://developer.apple.com/documentation/uikit/uiusernotificationsettings
- UIKit
- UIUserNotificationSettings Deprecated
Class
UIUserNotificationSettings
The types of notifications that can be displayed to the user by your app.
iOS 8.0–10.0DeprecatediPadOS 8.0–10.0DeprecatedMac Catalyst 13.1–13.1Deprecated
@MainActor class UIUserNotificationSettings
Overview
Apps that use visible or audible alerts in conjunction with a local or push notification must register the types of alerts they employ. UIKit correlates the information you provide with the user’s preferences to determine what types of alerts your app is allowed to employ.
Use this class to encapsulate your initial registration request and to view the request results. After creating an instance of this class and specifying your preferred settings, call the registerUserNotificationSettings(_:) method of the UIApplication class to register those settings. After checking your request against the user preferences, the app delivers the results to the application(_:didRegister:) method of its app delegate. The object passed to that method specifies the types of notifications that your app is allowed to use.
In addition to registering your app’s alert types, you can also use this class to register groups of custom actions to display in conjunction with local or push notifications. Custom actions represent immediate tasks your app can perform in response to the notification. You define groups of actions and associate the entire group with a given notification. When the corresponding alert is displayed, the system adds buttons for each action you specified. When the user taps the button for one of the actions, the system wakes your app and calls the application(_:handleActionWithIdentifier:forRemoteNotification:completionHandler:) or application(_:handleActionWithIdentifier:for:completionHandler:) method of its app delegate. Use those methods to perform the requested action.
Topics
Creating a settings object
Creates and returns a settings object that you can use to register your requested notification and action types.
Getting the configured settings
var types: UIUserNotificationType
A bitmask of the notification types that your app is allowed to use.
The app’s registered groups of actions.
Constants
struct UIUserNotificationType
Constants indicating how the app alerts the user when a local or push notification arrives.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendable
See Also
Deprecated classes
class UIActionSheet
A view that presents a set of alternatives for how to proceed with a task.
Deprecated
class UIAlertView
A view that displays an alert message.
class UIDocumentMenuViewController
A list of all the available document providers for a given file type and mode, in addition to custom menu items that you add.
class UILocalNotification
A notification that an app can schedule for presentation at a specific date and time.
class UIMenuController
The menu interface for the Cut, Copy, Paste, Select, Select All, and Delete commands.
class UIMenuItem
A custom item in the editing menu managed by the menu controller.
class UIMutableUserNotificationAction
A modifiable version of the user notification action class.
class UIMutableUserNotificationCategory
Information about custom actions that your app can perform in response to a local or push notification.
class UIPopoverController
An object that manages the presentation of content in a popover.
class UIPreviewAction
A preview action, or peek quick action, that displays below a peek when a user swipes the peek upward.
class UIPreviewActionGroup
A group of one or more child quick actions, each an instance of the preview action class.
class UISearchDisplayController
An object that manages the display of a search bar, along with a table view that displays search results.
class UIStoryboardPopoverSegue
A specific type of segue for presenting content in a popover.
class UIUserNotificationAction
A custom action that your app can perform in response to a remote or local notification.
class UIUserNotificationCategory
https://developer.apple.com/documentation/uikit/uiaccelerometerdelegate
- UIKit
- UIAccelerometerDelegate Deprecated
Protocol
UIAccelerometerDelegate
The interface for receiving acceleration-related data from the system.
iOS 2.0–13.0DeprecatediPadOS 2.0–13.0DeprecatedMac Catalyst 13.1–13.1Deprecated
@MainActor protocol UIAccelerometerDelegate : NSObjectProtocol
Relationships
Inherits From
NSObjectProtocol
See Also
Deprecated protocols
protocol UIActionSheetDelegate
The interface for the delegate of an action sheet object.
Deprecated
protocol UIAlertViewDelegate
The interface for the delegate of an alert view object.
protocol UIPopoverControllerDelegate
The interface for the delegate of a popover controller object.
protocol UISearchDisplayDelegate
The interface for the delegate of a search display controller.
protocol UIViewControllerPreviewing
A set of methods that define the interface for configuring a previewing view controller on devices that support 3D Touch.
protocol UIViewControllerPreviewingDelegate
A set of methods used by the delegate to respond, with a preview view controller and a commit view controller, to the user pressing a view object on the screen of a device that supports 3D Touch.
https://developer.apple.com/documentation/uikit/uiactionsheetdelegate
- UIKit
- UIActionSheetDelegate Deprecated
Protocol
UIActionSheetDelegate
The interface for the delegate of an action sheet object.
iOSiPadOSMac CatalystvisionOS
@MainActor protocol UIActionSheetDelegate : NSObjectProtocol
Overview
The delegate implements the button actions and any other custom behavior. Some of the methods defined in this protocol are optional.
If you add your own buttons or customize the behavior of an action sheet, implement a delegate conforming to this protocol to handle the corresponding delegate messages. Use the delegate property of the action sheet object to specify one of your application objects as the delegate.
If you add your own buttons to an action sheet, the delegate must implement the actionSheet(_:clickedButtonAt:) message to respond when those buttons are clicked; otherwise, your custom buttons do nothing. The action sheet is automatically dismissed after the actionSheet(_:clickedButtonAt:) delegate method is invoked.
Optionally, you can implement the actionSheetCancel(_:) method to take the appropriate action when the system cancels your action sheet. If the delegate does not implement this method, the default behavior is to simulate the user clicking the cancel button and closing the view.
You can also optionally augment the behavior of presenting and dismissing action sheets using the methods in Customizing behavior.
Topics
Responding to actions
func actionSheet(UIActionSheet, clickedButtonAt: Int)
Sent to the delegate when the user clicks a button on an action sheet.
Customizing behavior
func willPresent(UIActionSheet)
Sent to the delegate before an action sheet is presented to the user.
func didPresent(UIActionSheet)
Sent to the delegate after an action sheet is presented to the user.
func actionSheet(UIActionSheet, willDismissWithButtonIndex: Int)
Sent to the delegate before an action sheet is dismissed.
func actionSheet(UIActionSheet, didDismissWithButtonIndex: Int)
Sent to the delegate after an action sheet is dismissed from the screen.
Canceling
func actionSheetCancel(UIActionSheet)
Sent to the delegate before an action sheet is canceled.
Relationships
Inherits From
NSObjectProtocol
Conforming Types
UIDocumentInteractionController
See Also
Deprecated protocols
protocol UIAccelerometerDelegate
The interface for receiving acceleration-related data from the system.
Deprecated
protocol UIAlertViewDelegate
The interface for the delegate of an alert view object.
protocol UIPopoverControllerDelegate
The interface for the delegate of a popover controller object.
protocol UISearchDisplayDelegate
The interface for the delegate of a search display controller.
protocol UIViewControllerPreviewing
A set of methods that define the interface for configuring a previewing view controller on devices that support 3D Touch.
protocol UIViewControllerPreviewingDelegate
A set of methods used by the delegate to respond, with a preview view controller and a commit view controller, to the user pressing a view object on the screen of a device that supports 3D Touch.
https://developer.apple.com/documentation/uikit/uialertviewdelegate
- UIKit
- UIAlertViewDelegate Deprecated
Protocol
UIAlertViewDelegate
The interface for the delegate of an alert view object.
iOSiPadOSMac Catalyst
@MainActor protocol UIAlertViewDelegate : NSObjectProtocol
Overview
The delegate implements the button actions and any other custom behavior. Some of the methods defined in this protocol are optional.
If you add your own buttons or customize the behavior of an alert view, implement a delegate conforming to this protocol to handle the corresponding delegate messages. Use the delegate property of an alert view to specify one of your application objects as the delegate.
If you add your own buttons to an alert view, the delegate must implement the alertView(_:clickedButtonAt:) message to respond when those buttons are clicked; otherwise, your custom buttons do nothing. The alert view is automatically dismissed after the alertView(_:clickedButtonAt:) delegate method is invoked.
Optionally, you can implement the alertViewCancel(_:) method to take the appropriate action when the system cancels your alert view. If the delegate doesn’t implement this method, the default behavior is to simulate the user clicking the cancel button and closing the view.
You can also optionally augment the behavior of presenting and dismissing alert views using the methods in Customizing behavior.
Topics
Responding to actions
func alertView(UIAlertView, clickedButtonAt: Int)
Sent to the delegate when the user clicks a button on an alert view.
Customizing behavior
Sent to the delegate to determine whether the first non-cancel button in the alert should be enabled.
func willPresent(UIAlertView)
Sent to the delegate before a model view is presented to the user.
func didPresent(UIAlertView)
Sent to the delegate after an alert view is presented to the user.
func alertView(UIAlertView, willDismissWithButtonIndex: Int)
Sent to the delegate before an alert view is dismissed.
func alertView(UIAlertView, didDismissWithButtonIndex: Int)
Sent to the delegate after an alert view is dismissed from the screen.
Canceling
func alertViewCancel(UIAlertView)
Sent to the delegate before an alert view is canceled.
Relationships
Inherits From
NSObjectProtocol
See Also
Deprecated protocols
protocol UIAccelerometerDelegate
The interface for receiving acceleration-related data from the system.
Deprecated
protocol UIActionSheetDelegate
The interface for the delegate of an action sheet object.
protocol UIPopoverControllerDelegate
The interface for the delegate of a popover controller object.
protocol UISearchDisplayDelegate
The interface for the delegate of a search display controller.
protocol UIViewControllerPreviewing
A set of methods that define the interface for configuring a previewing view controller on devices that support 3D Touch.
protocol UIViewControllerPreviewingDelegate
A set of methods used by the delegate to respond, with a preview view controller and a commit view controller, to the user pressing a view object on the screen of a device that supports 3D Touch.
https://developer.apple.com/documentation/uikit/uipopovercontrollerdelegate
- UIKit
- UIPopoverControllerDelegate Deprecated
Protocol
UIPopoverControllerDelegate
The interface for the delegate of a popover controller object.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor protocol UIPopoverControllerDelegate : NSObjectProtocol
Overview
Popover controllers notify their delegate whenever user interactions would cause the dismissal of the popover and, in some cases, give the user a chance to prevent that dismissal.
For more information about the UIPopoverController class, see UIPopoverController.
Topics
Responding to popover position changes
Tells the delegate that the popover controller needs to change the popover’s location in its view.
Managing the popover’s dismissal
Asks the delegate if the popover should be dismissed.
func popoverControllerDidDismissPopover(UIPopoverController)
Tells the delegate that the popover was dismissed.
Relationships
Inherits From
NSObjectProtocol
See Also
Deprecated protocols
protocol UIAccelerometerDelegate
The interface for receiving acceleration-related data from the system.
Deprecated
protocol UIActionSheetDelegate
The interface for the delegate of an action sheet object.
protocol UIAlertViewDelegate
The interface for the delegate of an alert view object.
protocol UISearchDisplayDelegate
The interface for the delegate of a search display controller.
protocol UIViewControllerPreviewing
A set of methods that define the interface for configuring a previewing view controller on devices that support 3D Touch.
protocol UIViewControllerPreviewingDelegate
A set of methods used by the delegate to respond, with a preview view controller and a commit view controller, to the user pressing a view object on the screen of a device that supports 3D Touch.
https://developer.apple.com/documentation/uikit/uisearchdisplaydelegate
- UIKit
- UISearchDisplayDelegate Deprecated
Protocol
UISearchDisplayDelegate
The interface for the delegate of a search display controller.
iOSiPadOSMac Catalyst
@MainActor protocol UISearchDisplayDelegate : NSObjectProtocol
Overview
This protocol defines delegate methods for UISearchDisplayController objects.
Topics
Responding to search state change
func searchDisplayControllerWillBeginSearch(UISearchDisplayController)
Tells the delegate that the controller is about to begin searching.
func searchDisplayControllerDidBeginSearch(UISearchDisplayController)
Tells the delegate that the controller has started searching.
func searchDisplayControllerWillEndSearch(UISearchDisplayController)
Tells the delegate that the controller is about to end searching.
func searchDisplayControllerDidEndSearch(UISearchDisplayController)
Tells the delegate that the controller has finished searching.
Loading and unloading the table view
func searchDisplayController(UISearchDisplayController, didLoadSearchResultsTableView: UITableView)
Tells the delegate that the controller has loaded its table view.
func searchDisplayController(UISearchDisplayController, willUnloadSearchResultsTableView: UITableView)
Tells the delegate that the controller is about to unload its table view.
Showing and hiding the table view
func searchDisplayController(UISearchDisplayController, willShowSearchResultsTableView: UITableView)
Tells the delegate that the controller is about to display its table view.
func searchDisplayController(UISearchDisplayController, didShowSearchResultsTableView: UITableView)
Tells the delegate that the controller just displayed its table view.
func searchDisplayController(UISearchDisplayController, willHideSearchResultsTableView: UITableView)
Tells the delegate that the controller is about to hide its table view.
func searchDisplayController(UISearchDisplayController, didHideSearchResultsTableView: UITableView)
Tells the delegate that the controller just hid its table view.
Responding to changes in search criteria
Asks the delegate if the table view should be reloaded for a given search string.
Asks the delegate if the table view should be reloaded for a given scope.
Relationships
Inherits From
NSObjectProtocol
See Also
Deprecated protocols
protocol UIAccelerometerDelegate
The interface for receiving acceleration-related data from the system.
Deprecated
protocol UIActionSheetDelegate
The interface for the delegate of an action sheet object.
protocol UIAlertViewDelegate
The interface for the delegate of an alert view object.
protocol UIPopoverControllerDelegate
The interface for the delegate of a popover controller object.
protocol UIViewControllerPreviewing
A set of methods that define the interface for configuring a previewing view controller on devices that support 3D Touch.
protocol UIViewControllerPreviewingDelegate
A set of methods used by the delegate to respond, with a preview view controller and a commit view controller, to the user pressing a view object on the screen of a device that supports 3D Touch.
https://developer.apple.com/documentation/uikit/uiviewcontrollerpreviewing
- UIKit
- UIViewControllerPreviewing Deprecated
Protocol
UIViewControllerPreviewing
A set of methods that define the interface for configuring a previewing view controller on devices that support 3D Touch.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor protocol UIViewControllerPreviewing : NSObjectProtocol
Overview
The system returns a context object conforming to this protocol when you call a view controller’s registerForPreviewing(with:sourceView:) method. This method registers the view controller to participate in 3D Touch preview (peek) and commit (pop) behaviors.
To learn about 3D Touch, read Adopting 3D Touch on iPhone.
Topics
Configuring a source view for a 3D Touch previewing view controller
var sourceRect: CGRect
The rectangle, in the source view’s coordinate system, that responds to a 3D Touch by a user and remains visually sharp while surrounding content blurs.
Required
var previewingGestureRecognizerForFailureRelationship: UIGestureRecognizer
A gesture recognizer suitable for setting up failure requirements for a preview’s (peek’s) gestures.
Accessing properties of a 3D Touch previewing view controller
var delegate: any UIViewControllerPreviewingDelegate
The previewing view controller’s delegate for managing preview (peek) and commit (pop) view controllers.
var sourceView: UIView
A source view, in a previewing view controller’s view hierarchy, responds to a 3D Touch by the user.
Relationships
Inherits From
NSObjectProtocol
See Also
Deprecated protocols
protocol UIAccelerometerDelegate
The interface for receiving acceleration-related data from the system.
Deprecated
protocol UIActionSheetDelegate
The interface for the delegate of an action sheet object.
protocol UIAlertViewDelegate
The interface for the delegate of an alert view object.
protocol UIPopoverControllerDelegate
The interface for the delegate of a popover controller object.
protocol UISearchDisplayDelegate
The interface for the delegate of a search display controller.
protocol UIViewControllerPreviewingDelegate
A set of methods used by the delegate to respond, with a preview view controller and a commit view controller, to the user pressing a view object on the screen of a device that supports 3D Touch.
https://developer.apple.com/documentation/uikit/uiviewcontrollerpreviewingdelegate
- UIKit
- UIViewControllerPreviewingDelegate Deprecated
Protocol
UIViewControllerPreviewingDelegate
A set of methods used by the delegate to respond, with a preview view controller and a commit view controller, to the user pressing a view object on the screen of a device that supports 3D Touch.
@MainActor protocol UIViewControllerPreviewingDelegate : NSObjectProtocol
Overview
To learn about 3D Touch, read Adopting 3D Touch on iPhone.
Topics
Providing preview and commit views for 3D Touch
Called when the user has pressed a source view in a previewing view controller, thereby obtaining a surrounding blur to indicate that a preview (peek) is available.
Required
func previewingContext(any UIViewControllerPreviewing, commit: UIViewController)
Called to let you prepare the presentation of a commit (pop) view from your commit view controller.
Relationships
Inherits From
NSObjectProtocol
See Also
Deprecated protocols
protocol UIAccelerometerDelegate
The interface for receiving acceleration-related data from the system.
Deprecated
protocol UIActionSheetDelegate
The interface for the delegate of an action sheet object.
protocol UIAlertViewDelegate
The interface for the delegate of an alert view object.
protocol UIPopoverControllerDelegate
The interface for the delegate of a popover controller object.
protocol UISearchDisplayDelegate
The interface for the delegate of a search display controller.
protocol UIViewControllerPreviewing
A set of methods that define the interface for configuring a previewing view controller on devices that support 3D Touch.
https://developer.apple.com/documentation/uikit/uistatusbaranimation
https://developer.apple.com/documentation/uikit/uiapplicationmain(::::)-9jjn8
https://developer.apple.com/documentation/uikit/implementing-peek-and-pop
- UIKit
- Deprecated symbols
- Implementing Peek and Pop
Sample Code
Implementing Peek and Pop
Accelerate actions in your app by providing shortcuts to preview content in detail view controllers.
Download
Xcode 10.2+
Overview
This sample project demonstrates previewing content and providing quick shortcuts to functionality using Peek and Pop APIs. The app uses a table view to display a list of colors and tapping any row in the table navigates to a detail view controller showing the color. The app uses 3D Touch on the table view rows to allow users to peek at the content without placing it on the navigation stack.
Colors can also be starred or unstarred. Starred colors are shown with a solid filled colored star icon to the left of the name and unstarred colors have a hollow star. Users can toggle whether a color is starred using one of two methods: they can either tap a button in the navigation bar of the detail view, or use 3D Touch to peek at the content. Swiping up while in 3D Touch lets the user access a Peek Quick Action.
The app uses a tab bar controller to demonstrate two different methods for implementing Peek and Pop. The first tab contains the ColorsViewControllerStoryboard view controller, which configures Peek and Pop using the segue in Main.storyboard. The second tab contains the ColorsViewControllerCode view controller to achieve the same functionality, but in code.
Both ColorsViewControllerStoryboard and ColorsViewControllerCode are subclasses of ColorsViewControllerBase, which contains the implementation of everything necessary to display the table view and handle the standard segue.
Peek and Pop from a storyboard
The storyboard uses a Show segue with Peek and Pop enabled to navigate from the ColorViewControllerStoryboard to ColorItemViewController. This is done by selecting the Show segue, and turning on “Preview & Commit Segues” next to Peek & Pop in the Attributes inspector.
When configuring the ColorItemViewController, enable the “Use Preferred Explicit Size” option in the View Controller section of the Attributes inspector. Set the “Content Size” to have 0 width and an appropriate height. Zero width configures the view controller to automatically resize to the device width when the user peeks at the content.
When implementing the ColorsViewControllerBase view controller, resist the temptation of using either indexPathForSelectedRow or indexPathsForSelectedRows when preparing to execute a segue. If you configure the storyboard with the default implementation of Peek and Pop, these methods return nil at the time of segue execution. Instead, use the segue’s sender property to access the cell initiating the peek.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let selectedTableViewCell = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: selectedTableViewCell) else { preconditionFailure("Expected sender to be a valid table view cell") }
guard let colorItemViewController = segue.destination as? ColorItemViewController else { preconditionFailure("Expected a ColorItemViewController") }
// Pass over a reference to the ColorData object and the specific ColorItem being viewed. colorItemViewController.colorData = colorData colorItemViewController.colorItem = colorData.colors[indexPath.row] }
Peek and Pop in code
The ColorsViewControllerCode view controller adds code to manually register for Peek and Pop instead of using the storyboard to customize the segue. Call registerForPreviewing(with:sourceView:) to register a class which implements the UIViewControllerPreviewingDelegate protocol, and then pass in a view which responds to the 3D Touch.
override func viewDidLoad() { super.viewDidLoad()
registerForPreviewing(with: self, sourceView: tableView) }
The protocol requires the implementation of two methods. When the system detects the 3D Touch, it calls previewingContext(_:viewControllerForLocation:), passing a previewingContext object that conforms to the UIViewControllerPreviewing protocol. Use this method to configure and pass back a view controller for the peek.
// First, get the index path and view for the previewed cell. guard let indexPath = tableView.indexPathForRow(at: location), let cell = tableView.cellForRow(at: indexPath) else { return nil }
// Enable blurring of other UI elements, and a zoom in animation while peeking. previewingContext.sourceRect = cell.frame
// Create and configure an instance of the color item view controller to show for the peek. guard let viewController = storyboard?.instantiateViewController(withIdentifier: "ColorItemViewController") as? ColorItemViewController else { preconditionFailure("Expected a ColorItemViewController") }
// Pass over a reference to the ColorData object and the specific ColorItem being viewed. viewController.colorData = colorData viewController.colorItem = colorData.colors[indexPath.row]
return viewController }
When the system detects enough pressure in the 3D Touch to pop the view controller, it calls previewingContext(_:commit:). Take the passed in view controller and present to the user.
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { // Push the configured view controller onto the navigation stack. navigationController?.pushViewController(viewControllerToCommit, animated: true) }
Implement Peek Quick Actions
To enable Peek Quick Actions for the ColorItemViewController, you must override the default implementation of the previewActionItems property to return an array of UIPreviewAction or UIPreviewActionGroup objects.
Both a star/unstar action and a delete action are available as quick actions using the following code:
override var previewActionItems: [UIPreviewActionItem] { let starAction = UIPreviewAction(title: starButtonTitle(), style: .default, handler: { [unowned self] (_, _) in guard let colorItem = self.colorItem else { preconditionFailure("Expected a color item") }
colorItem.starred.toggle() })
let deleteAction = UIPreviewAction(title: "Delete", style: .destructive) { [unowned self] (_, _) in guard let colorData = self.colorData else { preconditionFailure("Expected a reference to the color data container") }
guard let colorItem = self.colorItem else { preconditionFailure("Expected a color item") }
colorData.delete(colorItem) }
return [ starAction, deleteAction ] }
The star/unstar action is shown with a default style and the delete action is shown as being destructive.
It’s important to ensure that your app’s features are still available to devices that do not support 3D Touch. In this sample, both the star/unstar and the delete functionality remain available by navigating into the ColorItemViewController and tapping buttons in the navigation bar. The Peek Quick Action provides a more convenient way to access that feature.
https://developer.apple.com/documentation/uikit/uiactionsheet)
https://developer.apple.com/documentation/uikit/uialertview)
https://developer.apple.com/documentation/uikit/uidocumentmenuviewcontroller)
https://developer.apple.com/documentation/uikit/uilocalnotification)
https://developer.apple.com/documentation/uikit/uimenucontroller)
https://developer.apple.com/documentation/uikit/uimenuitem)
https://developer.apple.com/documentation/uikit/uimutableusernotificationaction)
https://developer.apple.com/documentation/uikit/uimutableusernotificationcategory)
https://developer.apple.com/documentation/uikit/uipopovercontroller)
https://developer.apple.com/documentation/uikit/uipreviewaction)
https://developer.apple.com/documentation/uikit/uipreviewactiongroup)
https://developer.apple.com/documentation/uikit/uisearchdisplaycontroller)
https://developer.apple.com/documentation/uikit/uistoryboardpopoversegue)
https://developer.apple.com/documentation/uikit/uiusernotificationaction)
https://developer.apple.com/documentation/uikit/uiusernotificationcategory)
https://developer.apple.com/documentation/uikit/uiusernotificationsettings)
https://developer.apple.com/documentation/uikit/uiaccelerometerdelegate)
https://developer.apple.com/documentation/uikit/uiactionsheetdelegate)
https://developer.apple.com/documentation/uikit/uialertviewdelegate)
https://developer.apple.com/documentation/uikit/uipopovercontrollerdelegate)
https://developer.apple.com/documentation/uikit/uisearchdisplaydelegate)
https://developer.apple.com/documentation/uikit/uiviewcontrollerpreviewing)
https://developer.apple.com/documentation/uikit/uiviewcontrollerpreviewingdelegate)
https://developer.apple.com/documentation/uikit/uistatusbaranimation)
https://developer.apple.com/documentation/uikit/uiapplicationmain(::::)-9jjn8)
https://developer.apple.com/documentation/uikit/implementing-peek-and-pop)
https://developer.apple.com/documentation/uikit/uitextformattingviewcontroller/componentkey
- UIKit
- UITextFormattingViewController
- UITextFormattingViewController.ComponentKey
Structure
UITextFormattingViewController.ComponentKey
struct ComponentKey
Topics
Initializers
init(rawValue: String)
Relationships
Conforms To
EquatableHashableRawRepresentableSendableSendableMetatype
See Also
Data Types
struct Highlight
struct TextAlignment
struct TextList
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uitextformattingviewcontroller/highlight
- UIKit
- UITextFormattingViewController
- UITextFormattingViewController.Highlight
Structure
UITextFormattingViewController.Highlight
struct Highlight
Topics
Initializers
init(rawValue: String)
Relationships
Conforms To
EquatableHashableRawRepresentableSendableSendableMetatype
See Also
Data Types
struct ComponentKey
struct TextAlignment
struct TextList
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uitextformattingviewcontroller/textalignment
- UIKit
- UITextFormattingViewController
- UITextFormattingViewController.TextAlignment
Structure
UITextFormattingViewController.TextAlignment
struct TextAlignment
Topics
Initializers
init(nsTextAlignment: NSTextAlignment)
init(rawValue: String)
Instance Properties
var nsTextAlignment: NSTextAlignment
Relationships
Conforms To
EquatableHashableRawRepresentableSendableSendableMetatype
See Also
Data Types
struct ComponentKey
struct Highlight
struct TextList
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uitextformattingviewcontroller/textlist
- UIKit
- UITextFormattingViewController
- UITextFormattingViewController.TextList
Structure
UITextFormattingViewController.TextList
struct TextList
Topics
Initializers
init(rawValue: String)
Relationships
Conforms To
EquatableHashableRawRepresentableSendableSendableMetatype
See Also
Data Types
struct ComponentKey
struct Highlight
struct TextAlignment
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uitextformattingviewcontroller/componentkey)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uitextformattingviewcontroller/highlight)
https://developer.apple.com/documentation/uikit/uitextformattingviewcontroller/textalignment)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uitextformattingviewcontroller/textlist)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiaccessibility/expandedstatus
- UIKit
- UIAccessibility
- UIAccessibility.ExpandedStatus
Enumeration
UIAccessibility.ExpandedStatus
enum ExpandedStatus
Topics
Enumeration Cases
case collapsed
case expanded
case unsupported
Initializers
init?(rawValue: Int)
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Enumerations
enum ComponentSize
enum UIFocusItemDeferralMode
https://developer.apple.com/documentation/uikit/uitextformattingviewcontroller/componentsize
- UIKit
- UITextFormattingViewController
- UITextFormattingViewController.ComponentSize
Enumeration
UITextFormattingViewController.ComponentSize
enum ComponentSize
Topics
Enumeration Cases
case automatic
case extraLarge
case large
case mini
case regular
case small
Initializers
init?(rawValue: Int)
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Enumerations
enum ExpandedStatus
enum UIFocusItemDeferralMode
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uifocusitemdeferralmode
- UIKit
- UIFocusItemDeferralMode
Enumeration
UIFocusItemDeferralMode
enum UIFocusItemDeferralMode
Topics
Enumeration Cases
case always
Always defer focus for this item, even if deferral is disabled right now. This means a programmatic update to this item would result in focus disappearing until the user interacts with the focus engine again.
case automatic
Use the system default behavior.
case never
Never defer focus for this item. When a programmatic focus update lands on this item, it will always be and appear focused even if focus deferral is currently enabled.
Initializers
init?(rawValue: Int)
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Enumerations
enum ExpandedStatus
enum ComponentSize
https://developer.apple.com/documentation/uikit/uiaccessibility/expandedstatus)
https://developer.apple.com/documentation/uikit/uitextformattingviewcontroller/componentsize)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uifocusitemdeferralmode)
https://developer.apple.com/documentation/uikit/uiconfigurationtextattributestransformer-swift.struct/init(_:)
#app-main)
- UIKit
- UIConfigurationTextAttributesTransformer
- init(_:)
Initializer
init(_:)
Creates a new text attributes transformer.
Mac CatalystvisionOS
Parameters
transform
A closure that defines the text transformation.
https://developer.apple.com/documentation/uikit/uiconfigurationtextattributestransformer-swift.struct/transform
- UIKit
- UIConfigurationTextAttributesTransformer
- transform
Instance Property
transform
A closure that defines the text transformation.
Mac CatalystvisionOS
Discussion
This closure accepts a container with the current text attributes and returns a container with the new text attributes.
https://developer.apple.com/documentation/uikit/uiconfigurationtextattributestransformer-swift.struct/callasfunction(_:)
#app-main)
- UIKit
- UIConfigurationTextAttributesTransformer
- callAsFunction(_:)
Instance Method
callAsFunction(_:)
Calls the transform closure of the text attributes transformer.
Mac CatalystvisionOS
Parameters
input
The current attributes container for a string.
Return Value
A new, transformed attributes container.
Discussion
Using this syntax, you can call the text attributes transformer type as if it were a closure:
var container = AttributeContainer() container.backgroundColor = UIColor.blue let transformer = UIConfigurationTextAttributesTransformer { incoming in var outgoing = incoming outgoing.backgroundColor = incoming.backgroundColor?.withAlphaComponent(0.6) return outgoing } let transformed = transformer.callAsFunction(container)
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/title
- UIKit
- UIButton
- UIButton.Configuration
- title
Instance Property
title
The text of the title label the button displays.
Mac CatalystvisionOS
var title: String? { get set }
Discussion
This property matches the string value of the attributedTitle property. To change the button title when the button state changes, use configurationUpdateHandler or updateConfiguration().
See Also
Configuring titles
var subtitle: String?
The text the subtitle label of the button displays.
var attributedTitle: AttributedString?
The text and style attributes for the button’s title label.
var attributedSubtitle: AttributedString?
The text and style attributes for the button’s subtitle label.
var titleTextAttributesTransformer: UIConfigurationTextAttributesTransformer?
A structure to update the attributed title when the button state changes.
var subtitleTextAttributesTransformer: UIConfigurationTextAttributesTransformer?
A structure to update the attributed subtitle when the button state changes.
struct UIConfigurationTextAttributesTransformer
Defines a text transformation that can affect the visual appearance of a string.
var titlePadding: CGFloat
The distance between the title and subtitle labels.
var titleAlignment: UIButton.Configuration.TitleAlignment
The text alignment the button uses to lay out the title and subtitle.
enum TitleAlignment
Specifies how to align a button’s title and subtitle.
var titleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s title.
var subtitleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s subtitle.
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/subtitle
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/attributedtitle
- UIKit
- UIButton
- UIButton.Configuration
- attributedTitle
Instance Property
attributedTitle
The text and style attributes for the button’s title label.
Mac CatalystvisionOS
var attributedTitle: AttributedString? { get set }
Discussion
The configuration sets the title property to match the string value of this attributed string. To change the button title when the button state changes, use configurationUpdateHandler or updateConfiguration().
See Also
Configuring titles
var title: String?
The text of the title label the button displays.
var subtitle: String?
The text the subtitle label of the button displays.
var attributedSubtitle: AttributedString?
The text and style attributes for the button’s subtitle label.
var titleTextAttributesTransformer: UIConfigurationTextAttributesTransformer?
A structure to update the attributed title when the button state changes.
var subtitleTextAttributesTransformer: UIConfigurationTextAttributesTransformer?
A structure to update the attributed subtitle when the button state changes.
struct UIConfigurationTextAttributesTransformer
Defines a text transformation that can affect the visual appearance of a string.
var titlePadding: CGFloat
The distance between the title and subtitle labels.
var titleAlignment: UIButton.Configuration.TitleAlignment
The text alignment the button uses to lay out the title and subtitle.
enum TitleAlignment
Specifies how to align a button’s title and subtitle.
var titleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s title.
var subtitleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s subtitle.
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/attributedsubtitle
- UIKit
- UIButton
- UIButton.Configuration
- attributedSubtitle
Instance Property
attributedSubtitle
The text and style attributes for the button’s subtitle label.
Mac CatalystvisionOS
var attributedSubtitle: AttributedString? { get set }
Discussion
The configuration sets the subtitle property to match the string value of this attributed string. To change the button subtitle when the button state changes, use configurationUpdateHandler or updateConfiguration().
See Also
Configuring titles
var title: String?
The text of the title label the button displays.
var subtitle: String?
The text the subtitle label of the button displays.
var attributedTitle: AttributedString?
The text and style attributes for the button’s title label.
var titleTextAttributesTransformer: UIConfigurationTextAttributesTransformer?
A structure to update the attributed title when the button state changes.
var subtitleTextAttributesTransformer: UIConfigurationTextAttributesTransformer?
A structure to update the attributed subtitle when the button state changes.
struct UIConfigurationTextAttributesTransformer
Defines a text transformation that can affect the visual appearance of a string.
var titlePadding: CGFloat
The distance between the title and subtitle labels.
var titleAlignment: UIButton.Configuration.TitleAlignment
The text alignment the button uses to lay out the title and subtitle.
enum TitleAlignment
Specifies how to align a button’s title and subtitle.
var titleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s title.
var subtitleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s subtitle.
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/titletextattributestransformer
- UIKit
- UIButton
- UIButton.Configuration
- titleTextAttributesTransformer
Instance Property
titleTextAttributesTransformer
A structure to update the attributed title when the button state changes.
Mac CatalystvisionOS
var titleTextAttributesTransformer: UIConfigurationTextAttributesTransformer? { get set }
See Also
Configuring titles
var title: String?
The text of the title label the button displays.
var subtitle: String?
The text the subtitle label of the button displays.
var attributedTitle: AttributedString?
The text and style attributes for the button’s title label.
var attributedSubtitle: AttributedString?
The text and style attributes for the button’s subtitle label.
var subtitleTextAttributesTransformer: UIConfigurationTextAttributesTransformer?
A structure to update the attributed subtitle when the button state changes.
struct UIConfigurationTextAttributesTransformer
Defines a text transformation that can affect the visual appearance of a string.
var titlePadding: CGFloat
The distance between the title and subtitle labels.
var titleAlignment: UIButton.Configuration.TitleAlignment
The text alignment the button uses to lay out the title and subtitle.
enum TitleAlignment
Specifies how to align a button’s title and subtitle.
var titleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s title.
var subtitleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s subtitle.
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/subtitletextattributestransformer
- UIKit
- UIButton
- UIButton.Configuration
- subtitleTextAttributesTransformer
Instance Property
subtitleTextAttributesTransformer
A structure to update the attributed subtitle when the button state changes.
Mac CatalystvisionOS
var subtitleTextAttributesTransformer: UIConfigurationTextAttributesTransformer? { get set }
See Also
Configuring titles
var title: String?
The text of the title label the button displays.
var subtitle: String?
The text the subtitle label of the button displays.
var attributedTitle: AttributedString?
The text and style attributes for the button’s title label.
var attributedSubtitle: AttributedString?
The text and style attributes for the button’s subtitle label.
var titleTextAttributesTransformer: UIConfigurationTextAttributesTransformer?
A structure to update the attributed title when the button state changes.
struct UIConfigurationTextAttributesTransformer
Defines a text transformation that can affect the visual appearance of a string.
var titlePadding: CGFloat
The distance between the title and subtitle labels.
var titleAlignment: UIButton.Configuration.TitleAlignment
The text alignment the button uses to lay out the title and subtitle.
enum TitleAlignment
Specifies how to align a button’s title and subtitle.
var titleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s title.
var subtitleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s subtitle.
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/titlepadding
- UIKit
- UIButton
- UIButton.Configuration
- titlePadding
Instance Property
titlePadding
The distance between the title and subtitle labels.
Mac CatalystvisionOS
var titlePadding: CGFloat { get set }
Discussion
The title padding adjusts the distance between the title and subtitle labels.
See Also
Configuring titles
var title: String?
The text of the title label the button displays.
var subtitle: String?
The text the subtitle label of the button displays.
var attributedTitle: AttributedString?
The text and style attributes for the button’s title label.
var attributedSubtitle: AttributedString?
The text and style attributes for the button’s subtitle label.
var titleTextAttributesTransformer: UIConfigurationTextAttributesTransformer?
A structure to update the attributed title when the button state changes.
var subtitleTextAttributesTransformer: UIConfigurationTextAttributesTransformer?
A structure to update the attributed subtitle when the button state changes.
struct UIConfigurationTextAttributesTransformer
Defines a text transformation that can affect the visual appearance of a string.
var titleAlignment: UIButton.Configuration.TitleAlignment
The text alignment the button uses to lay out the title and subtitle.
enum TitleAlignment
Specifies how to align a button’s title and subtitle.
var titleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s title.
var subtitleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s subtitle.
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/titlealignment-swift.property
- UIKit
- UIButton
- UIButton.Configuration
- titleAlignment
Instance Property
titleAlignment
The text alignment the button uses to lay out the title and subtitle.
Mac CatalystvisionOS
var titleAlignment: UIButton.Configuration.TitleAlignment { get set }
Discussion
The title aligment can align the title and subtitle labels along the leading or trailing edges, or center them relative to each other.
See Also
Configuring titles
var title: String?
The text of the title label the button displays.
var subtitle: String?
The text the subtitle label of the button displays.
var attributedTitle: AttributedString?
The text and style attributes for the button’s title label.
var attributedSubtitle: AttributedString?
The text and style attributes for the button’s subtitle label.
var titleTextAttributesTransformer: UIConfigurationTextAttributesTransformer?
A structure to update the attributed title when the button state changes.
var subtitleTextAttributesTransformer: UIConfigurationTextAttributesTransformer?
A structure to update the attributed subtitle when the button state changes.
struct UIConfigurationTextAttributesTransformer
Defines a text transformation that can affect the visual appearance of a string.
var titlePadding: CGFloat
The distance between the title and subtitle labels.
enum TitleAlignment
Specifies how to align a button’s title and subtitle.
var titleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s title.
var subtitleLineBreakMode: NSLineBreakMode
The line break mode the button uses to lay out the button’s subtitle.
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/titlealignment-swift.enum
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/titlelinebreakmode
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/subtitlelinebreakmode
https://developer.apple.com/documentation/uikit/uiconfigurationtextattributestransformer-swift.struct/init(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiconfigurationtextattributestransformer-swift.struct/transform)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiconfigurationtextattributestransformer-swift.struct/callasfunction(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/title)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/subtitle)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/attributedtitle)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/attributedsubtitle)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/titletextattributestransformer)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/subtitletextattributestransformer)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/titlepadding)
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/titlealignment-swift.property)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/titlealignment-swift.enum)
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/titlelinebreakmode)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uibutton/configuration-swift.struct/subtitlelinebreakmode)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uideviceorientationislandscape(_:)
https://developer.apple.com/documentation/uikit/uideviceorientationisportrait(_:)
#app-main)
- UIKit
- UIDeviceOrientationIsPortrait(_:)
Function
UIDeviceOrientationIsPortrait(_:)
iOSiPadOSMac CatalystvisionOS
See Also
https://developer.apple.com/documentation/uikit/uideviceorientationisvalidinterfaceorientation(_:)
https://developer.apple.com/documentation/uikit/uiinterfaceorientationislandscape(_:)
https://developer.apple.com/documentation/uikit/uiinterfaceorientationisportrait(_:)
#app-main)
- UIKit
- UIInterfaceOrientationIsPortrait(_:)
Function
UIInterfaceOrientationIsPortrait(_:)
iOSiPadOSMac CatalystvisionOS
See Also
https://developer.apple.com/documentation/uikit/uiwritingtoolscoordinatortextanimationdebugdescription(_:)
#app-main)
- UIKit
- UIWritingToolsCoordinatorTextAnimationDebugDescription(_:)
Function
UIWritingToolsCoordinatorTextAnimationDebugDescription(_:)
See Also
https://developer.apple.com/documentation/uikit/uideviceorientationislandscape(_:))
https://developer.apple.com/documentation/uikit/uideviceorientationisportrait(_:))
https://developer.apple.com/documentation/uikit/uideviceorientationisvalidinterfaceorientation(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiinterfaceorientationislandscape(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiinterfaceorientationisportrait(_:))
https://developer.apple.com/documentation/uikit/uiwritingtoolscoordinatortextanimationdebugdescription(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/optimizing-your-ipad-app-for-mac).
https://developer.apple.com/documentation/uikit/customizing-a-document-based-app-s-launch-experience
https://developer.apple.com/documentation/uikit/uidocumentbrowserviewcontroller
- UIKit
- UIDocumentBrowserViewController
Class
UIDocumentBrowserViewController
A view controller for browsing and performing actions on documents that you store locally and in the cloud.
@MainActor class UIDocumentBrowserViewController
Mentioned in
Providing access to directories
Customizing the browser
Overview
With the document browser view controller, users can easily access and view their documents in the cloud. By default, the document browser can access both the system’s local file provider and its iCloud file provider.
The local file provider grants access to all the documents in the app’s Documents directory. Users can also access documents from another app’s Documents directory, if that app declares either the UISupportsDocumentBrowser key, or both the UIFileSharingEnabled and LSSupportsOpeningDocumentsInPlace keys in its Info.plist file. When the user opens a document from another app’s Documents directory, they edit the document in place, and save the changes to the other app’s Documents directory.
The iCloud file provider creates a folder for your app in the user’s iCloud Drive. Users can access documents from this folder, or from anywhere in their iCloud Drive. The system automatically handles access to iCloud for you, so you don’t need to enable your app’s iCloud capabilities.
Third-party storage services can also provide access to the documents they manage by implementing a File Provider extension (iOS 11 or later). For more information, see File Provider.
Topics
Creating a document browser
Give users access to their local or remote documents from within your app.
Initializes and returns a document browser view controller that can open the specified file types.
Creating new documents
var activeDocumentCreationIntent: UIDocument.CreationIntent?
The current intent that defines how your app creates a document.
Responding to browser events
var delegate: (any UIDocumentBrowserViewControllerDelegate)?
The document browser’s delegate.
protocol UIDocumentBrowserViewControllerDelegate
The protocol you implement to respond as the user interacts with the document browser.
Imports a document into the same location as an existing document.
Configuring a document browser
var allowsDocumentCreation: Bool
A Boolean value that determines whether the document browser can create new documents.
var allowsPickingMultipleItems: Bool
A Boolean value that determines whether the user can select and open more than one document at a time.
Reveals, and optionally imports, the document at the provided URL.
var contentTypesForRecentDocuments: [UTType]
Content types for browsing recent documents.
Modifying the browser’s appearance
var browserUserInterfaceStyle: UIDocumentBrowserViewController.BrowserUserInterfaceStyle
The visual style for the document browser.
enum BrowserUserInterfaceStyle
Styles that define the document browser’s appearance.
var additionalLeadingNavigationBarButtonItems: [UIBarButtonItem]
Additional bar button items that the document browser displays on the leading side of its navigation bar.
var additionalTrailingNavigationBarButtonItems: [UIBarButtonItem]
Additional bar button items that the document browser displays on the trailing side of its navigation bar.
var shouldShowFileExtensions: Bool
A Boolean value that determines whether the browser always shows file extensions.
var localizedCreateDocumentActionTitle: String
The title for the Create Document button.
var defaultDocumentAspectRatio: CGFloat
The aspect ratio for the Create Document button.
Adding custom actions
var customActions: [UIDocumentBrowserAction]
Custom document browser actions.
class UIDocumentBrowserAction
A custom action that you can create and add to a document browser’s Edit menu or navigation bar.
Animating transitions
Creates a transition controller that provides the standard system-loading and segue animations for the document browser.
class UIDocumentBrowserTransitionController
An object that implements the standard loading and transition animations for a document browser.
Renaming a document
Renames a document at the specified URL.
Handling errors
struct UIDocumentBrowserError
A structure that contains information about document browser errors.
enum Code
The error codes for document browser errors.
let UIDocumentBrowserErrorDomain: String
The error domain for document browser errors.
Deprecated symbols
init(forOpeningFilesWithContentTypes: [String]?)
Deprecated
var recentDocumentsContentTypes: [String]
var allowedContentTypes: [String]
The document types that the browser can open.
Relationships
Inherits From
UIViewController
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSExtensionRequestHandlingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIActivityItemsConfigurationProvidingUIAppearanceContainerUIContentContainerUIFocusEnvironmentUIPasteConfigurationSupportingUIResponderStandardEditActionsUIStateRestoringUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Documents and directories
Customizing a document-based app’s launch experience
Add unique elements to your app’s document launch scene.
Use a document picker to access the content of a directory outside your app’s container.
Building a document browser-based app
Use a document browser to provide access to the user’s text files.
Building a document browser app for custom file formats
Implement a custom document file format to manage user interactions with files on different cloud storage providers.
class UIDocumentViewController
A view controller that manages and presents a document stored locally or in the cloud.
class UIDocumentPickerViewController
A view controller that provides access to documents or destinations outside your app’s sandbox.
class UIDocumentInteractionController
A view controller that previews, opens, or prints files with a file format that your app can’t handle directly.
https://developer.apple.com/documentation/uikit/uidocument/init(fileurl:)
#app-main)
- UIKit
- UIDocument
- init(fileURL:)
Initializer
init(fileURL:)
Returns a document object initialized with its file-system location.
@MainActor init(fileURL url: URL)
Parameters
url
A file URL identifying the location in the application sandbox where document data is to be written. Passing in nil or an empty URL results in the throwing of an invalidArgumentException.
Return Value
A UIDocument object or nil if the object could not be created.
Discussion
After you create a document object and no file exists for it yet, you should next call the save(to:for:completionHandler:) to write the document to its file-system location in the application sandbox. If url locates an existing document file, call open(completionHandler:) after creating the document object. The second parameter of this method, the save operation constant, should be UIDocument.SaveOperation.forCreating when there is no document file yet. In the completion handler, if you want the document to be automatically synced with other devices you should ensure that its URL is based in a ubiquitous container; see Designing for Documents in iCloud for more information.
See Also
Related Documentation
var fileURL: URL
The file URL you use to initialize the document.
https://developer.apple.com/documentation/uikit/uidocument/filetype
- UIKit
- UIDocument
- fileType
Instance Property
fileType
The file type of the document.
@MainActor var fileType: String? { get }
Discussion
The file type is a uniform type identifier (UTI). UIKit derives the UTI from the filename-extension component of fileURL.
UIKit sets this property before it calls the completion handlers of the open(completionHandler:), save(to:for:completionHandler:), and revert(toContentsOf:completionHandler:). If, outside of these methods or their completion handlers, you want to wait for any pending file operations to complete before you access this property, you can call performAsynchronousFileAccess(_:) and access the property value in the block parameter.
See Also
Accessing document attributes
var fileURL: URL
The file URL you use to initialize the document.
var localizedName: String
The localized name of the document.
var fileModificationDate: Date?
The date and time your app last modified the document file.
var documentState: UIDocument.State
The current state of the document.
var progress: Progress?
The upload or download progress of a document.
https://developer.apple.com/documentation/uikit/uidocument/localizedname
- UIKit
- UIDocument
- localizedName
Instance Property
localizedName
The localized name of the document.
@MainActor var localizedName: String { get }
Discussion
By default, UIKit obtains the value from the filename component of fileURL. You can override the getter accessor method of this property to provide a custom name for presentation to the user, such as in error strings. See UIDocument for overriding advice.
UIKit sets this property before it calls the completion handlers of the open(completionHandler:), save(to:for:completionHandler:), and revert(toContentsOf:completionHandler:). If, outside of these methods or their completion handlers, you want to wait for any pending file operations to complete before you access this property, you can call performAsynchronousFileAccess(_:) and access the property value in the block parameter.
See Also
Accessing document attributes
var fileURL: URL
The file URL you use to initialize the document.
var fileType: String?
The file type of the document.
var fileModificationDate: Date?
The date and time your app last modified the document file.
var documentState: UIDocument.State
The current state of the document.
var progress: Progress?
The upload or download progress of a document.
https://developer.apple.com/documentation/uikit/uidocument/save(to:for:completionhandler:)
#app-main)
- UIKit
- UIDocument
- save(to:for:completionHandler:)
Instance Method
save(to:for:completionHandler:)
Saves document data to the specified location in the application sandbox.
@MainActor func save( to url: URL, for saveOperation: UIDocument.SaveOperation,
) @MainActor func save( to url: URL, for saveOperation: UIDocument.SaveOperation
Parameters
url
The file URL identifying the location in the application sandbox to write the document data to. Typically, this is the URL obtained from the fileURL property.
saveOperation
A constant that indicates whether the document file is being written the first time or whether it is being overwritten. See UIDocument.SaveOperation for details.
completionHandler
A block with code that is executed when the save operation concludes. The block returns no value and has one parameter:
success
true if the save operation succeeds, otherwise false.
This block is invoked on the calling queue.
Discussion
The default implementation of this method first calls the contents(forType:) method synchronously on the calling queue to get the document data to save. Then it calls the writeContents(_:andAttributes:safelyTo:for:) method on a background queue to perform the actual writing of the data to disk.
If you override this method, it’s recommended that you first call the superclass implementation of the method ( super). If you do not call super, you must do two things:
-
Call
performAsynchronousFileAccess(_:)to put the save operation on a background queue. -
In the block parameter, implement coordinated writing by using the
NSFileCoordinatorclass. -
From within the coordinated write, call
writeContents(_:andAttributes:safelyTo:for:).
See Also
Writing document data
Asynchronously closes the document after saving any changes.
Returns the document data to be saved.
Ensures that document data is written safely to a specified location in the application sandbox.
func writeContents(Any, to: URL, for: UIDocument.SaveOperation, originalContentsURL: URL?) throws
Writes the document data to disk at the sandbox location indicated by a file URL.
var savingFileType: String?
Returns the file type to use for saving a document.
Returns a dictionary of file attributes to associate with the document file when writing or updating it.
Returns a file extension to append to the file URL of the document file being written.
https://developer.apple.com/documentation/uikit/uidocument/open(completionhandler:)
#app-main)
- UIKit
- UIDocument
- open(completionHandler:)
Instance Method
open(completionHandler:)
Opens a document asynchronously.
@MainActor
Parameters
completionHandler
A block with code to execute after the open operation concludes. The block returns no value and has one parameter:
success
true if the open operation succeeds, otherwise false.
The block is invoked on the main queue.
Discussion
Call this method to begin the sequence of method calls that opens and reads a document asynchronously. The method obtains the file-system location of the document from the fileURL property. After the open operation concludes, the code in completionHandler is executed.
You can override this method if you want custom document-opening behavior, but if you do it’s recommended that you call the superclass implementation first ( super). If you don’t call super, you should use the NSFileCoordinator class to implement coordinated reading. The default implementation calls performAsynchronousFileAccess(_:) to schedule the document-reading work for execution on a background queue and then, from the dispatched block, performs file coordination. The queued task then calls read(from:).
See Also
Reading document data
func load(fromContents: Any, ofType: String?) throws
Loads the document data into the app’s data model.
func read(from: URL) throws
Reads the document data in a file at a specified location in the application sandbox.
https://developer.apple.com/documentation/uikit/uidocument/close(completionhandler:)
#app-main)
- UIKit
- UIDocument
- close(completionHandler:)
Instance Method
close(completionHandler:)
Asynchronously closes the document after saving any changes.
@MainActor
Parameters
completionHandler
A block with code to execute after the save-and-close operation concludes. The block returns no value and has one parameter:
success
true if any save operation succeeds, otherwise false.
The block is invoked on the main queue.
Discussion
You call this method to begin the sequence of method calls that saves a document safely and asynchronously. The file-system location of the document derives from the fileURL property. After the save operation concludes, the code in completionHandler is executed. In this code, you can close the document — for example, by removing the document’s view from the screen. Additionally, if the save operation didn’t succeed ( success is false), you can respond in an appropriate manner.
You typically wouldn’t override this method. The default implementation calls the autosave(completionHandler:) method.
See Also
Writing document data
Returns the document data to be saved.
Saves document data to the specified location in the application sandbox.
Ensures that document data is written safely to a specified location in the application sandbox.
func writeContents(Any, to: URL, for: UIDocument.SaveOperation, originalContentsURL: URL?) throws
Writes the document data to disk at the sandbox location indicated by a file URL.
var savingFileType: String?
Returns the file type to use for saving a document.
Returns a dictionary of file attributes to associate with the document file when writing or updating it.
Returns a file extension to append to the file URL of the document file being written.
https://developer.apple.com/documentation/uikit/uidocument/performasynchronousfileaccess(_:)
#app-main)
- UIKit
- UIDocument
- performAsynchronousFileAccess(_:)
Instance Method
performAsynchronousFileAccess(_:)
Schedules a document-reading or document-writing operation on a concurrent background queue.
@MainActor
Parameters
block
A block that’s invoked as the task to execute on the background queue. The block returns no value and takes no parameters.
Discussion
A typical UIDocument subclass — one that overrides contents(forType:) and load(fromContents:ofType:) — doesn’t need to call this method.
The default implementations of save(to:for:completionHandler:) and open(completionHandler:) call this method to serialize file access. If you override these methods and don’t call super, you should call this method to serialize file access on a background queue. If you directly call the read(from:) method, you should wrap that call in the block passed into performAsynchronousFileAccess(_:).
https://developer.apple.com/documentation/uikit/uidocument/revert(tocontentsof:completionhandler:)
#app-main)
- UIKit
- UIDocument
- revert(toContentsOf:completionHandler:)
Instance Method
revert(toContentsOf:completionHandler:)
Reverts a document to the most recent document data stored on-disk.
@MainActor func revert( toContentsOf url: URL,
) @MainActor
Parameters
url
A file URL locating the most recent version of the document file in the application’s sandbox.
completionHandler
A block with code to execute after the reversion operation concludes. The block returns no value and has one parameter:
success
true if the reversion operation succeeds, otherwise false.
The block is invoked on the main queue.
Discussion
You call this method to discard all unsaved document modifications and replace the document’s contents by reading the file or file package located by url. The default implementation brackets the reversion operation between disableEditing() and enableEditing() because the document shouldn’t accept user changes during this period. Subclasses that override this method must call the superclass implementation ( super) or use the NSFileCoordinator class to initiate a coordinated read.
https://developer.apple.com/documentation/uikit/uidocument/fileurl
- UIKit
- UIDocument
- fileURL
Instance Property
fileURL
The file URL you use to initialize the document.
@MainActor var fileURL: URL { get }
Discussion
The URL identifies the location of the document in the application sandbox. It includes the file extension, from which the file type is determined.
UIKit sets this property before it calls the completion handlers of the open(completionHandler:), save(to:for:completionHandler:), and revert(toContentsOf:completionHandler:). If, outside of these methods or their completion handlers, you want to wait for any pending file operations to complete before you access this property, you can call performAsynchronousFileAccess(_:) and access the property value in the block parameter.
See Also
Related Documentation
init(fileURL: URL)
Returns a document object initialized with its file-system location.
Accessing document attributes
var localizedName: String
The localized name of the document.
var fileType: String?
The file type of the document.
var fileModificationDate: Date?
The date and time your app last modified the document file.
var documentState: UIDocument.State
The current state of the document.
var progress: Progress?
The upload or download progress of a document.
https://developer.apple.com/documentation/uikit/uidocument/contents(fortype:)
https://developer.apple.com/documentation/uikit/uidocument/load(fromcontents:oftype:)
#app-main)
- UIKit
- UIDocument
- load(fromContents:ofType:)
Instance Method
load(fromContents:ofType:)
Loads the document data into the app’s data model.
@MainActor func load( fromContents contents: Any, ofType typeName: String? ) throws
Parameters
contents
An object encapsulating the document data to load. This object is either an instance of the NSData class (for flat files) or the FileWrapper class (for file packages).
typeName
The file type of the document, a Uniform Type Identifier (UTI) based on the file extension of fileURL. You can obtain the default value of the file type from the fileType property.
Discussion
Override this method to accept and load the data for a document. After UIDocument reads the document data from the file located at fileURL it calls your subclass, passing the data to the subclass in this method. This method is called on the queue that the open(completionHandler:) method was called on (typically, the main queue).
See Also
Reading document data
Opens a document asynchronously.
func read(from: URL) throws
Reads the document data in a file at a specified location in the application sandbox.
https://developer.apple.com/documentation/uikit/uidocument/hasunsavedchanges
- UIKit
- UIDocument
- hasUnsavedChanges
Instance Property
hasUnsavedChanges
A Boolean value that indicates whether the document has any unsaved changes.
@MainActor var hasUnsavedChanges: Bool { get }
Return Value
true if the document has unsaved changes, otherwise false.
Discussion
The default implementation of autosave(completionHandler:) initiates a save if this property returns true. Typical subclasses don’t need to override hasUnsavedChanges. To implement change tracking, they should instead use an UndoManager object (assigned to undoManager) to register changes or call updateChangeCount(_:) every time the user makes a change; UIKit then automatically determines whether there are unsaved changes.
See Also
Tracking changes and autosaving
func updateChangeCount(UIDocument.ChangeKind)
Updates the change counter by indicating the kind of change.
var undoManager: UndoManager!
The undo manager for the document.
Returns a change token for a specific save operation.
func updateChangeCount(withToken: Any, for: UIDocument.SaveOperation)
Updates the change count with reference to a change-count token passed in by UIKit.
Initiates automatic saving of documents with unsaved changes.
https://developer.apple.com/documentation/uikit/uidocument/undomanager
- UIKit
- UIDocument
- undoManager
Instance Property
undoManager
The undo manager for the document.
@MainActor var undoManager: UndoManager! { get set }
Discussion
This property holds the document’s undo manager (an UndoManager object). Accessing this property lazily creates a default undo manager if a custom undo manager hasn’t been set.
The undo manager for the document is registered as an observer of various UndoManager notifications so that it can call updateChangeCount(_:) as the user makes undoable changes to the document. When a subclass sets this property and implements registers changes with it, it doesn’t need to call updateChangeCount(_:) directly or (more rarely) override hasUnsavedChanges.
See Also
Tracking changes and autosaving
var hasUnsavedChanges: Bool
A Boolean value that indicates whether the document has any unsaved changes.
func updateChangeCount(UIDocument.ChangeKind)
Updates the change counter by indicating the kind of change.
Returns a change token for a specific save operation.
func updateChangeCount(withToken: Any, for: UIDocument.SaveOperation)
Updates the change count with reference to a change-count token passed in by UIKit.
Initiates automatic saving of documents with unsaved changes.
https://developer.apple.com/documentation/uikit/uidocument/updatechangecount(_:)
#app-main)
- UIKit
- UIDocument
- updateChangeCount(_:)
Instance Method
updateChangeCount(_:)
Updates the change counter by indicating the kind of change.
@MainActor func updateChangeCount(_ change: UIDocument.ChangeKind)
Parameters
change
A constant that indicates whether a change has been made, cleared, undone, or redone. See UIDocument.ChangeKind for more information.
Discussion
Calling this method can affect the value returned by hasUnsavedChanges. You shouldn’t need to call method this if you access an UndoManager object from the undoManager property (or assign a custom one to it) and register changes with the undo manager.
See Also
Tracking changes and autosaving
var hasUnsavedChanges: Bool
A Boolean value that indicates whether the document has any unsaved changes.
var undoManager: UndoManager!
The undo manager for the document.
Returns a change token for a specific save operation.
func updateChangeCount(withToken: Any, for: UIDocument.SaveOperation)
Updates the change count with reference to a change-count token passed in by UIKit.
Initiates automatic saving of documents with unsaved changes.
https://developer.apple.com/documentation/uikit/uidocument/documentstate
- UIKit
- UIDocument
- documentState
Instance Property
documentState
The current state of the document.
@MainActor var documentState: UIDocument.State { get }
Discussion
When document state changes, the UIDocument object stores a constant identifying the new state in this property. See the UIDocument.State enum for descriptions of these constants. To receive notifications about changes in document state, observe the stateChangedNotification notification.
See Also
Accessing document attributes
var fileURL: URL
The file URL you use to initialize the document.
var localizedName: String
The localized name of the document.
var fileType: String?
The file type of the document.
var fileModificationDate: Date?
The date and time your app last modified the document file.
var progress: Progress?
The upload or download progress of a document.
https://developer.apple.com/documentation/uikit/uidocument/statechangednotification
- UIKit
- UIDocument
- stateChangedNotification
Type Property
stateChangedNotification
A notification the document object posts when there’s a change in the state of the document.
nonisolated class let stateChangedNotification: NSNotification.Name
Discussion
When handling this notification, check the value of the documentState property to see what the new state is, and then proceed accordingly. There’s no userInfo dictionary.
https://developer.apple.com/documentation/uikit/uidocument/state/inconflict
https://developer.apple.com/documentation/uikit/uidocument/state/closed
- UIKit
- UIDocument
- UIDocument.State
- closed
Type Property
closed
There was an error in reading the document.
iOSiPadOSMac CatalystvisionOS
static var closed: UIDocument.State { get }
Discussion
The document has either not been successfully opened, or has been since closed. The document properties might not be valid.
See Also
Constants
static var normal: UIDocument.State
The document is open, editing is enabled, and there are no conflicts or errors associated with it.
static var inConflict: UIDocument.State
Conflicts exist for the document file located at the file URL.
static var savingError: UIDocument.State
There was an error in saving or reverting the document.
static var editingDisabled: UIDocument.State
The document is busy and it isn’t currently safe for user edits.
static var progressAvailable: UIDocument.State
The document is being downloaded or uploaded and progress information is available.
https://developer.apple.com/documentation/uikit/uidocument/state/savingerror
- UIKit
- UIDocument
- UIDocument.State
- savingError
Type Property
savingError
There was an error in saving or reverting the document.
iOSiPadOSMac CatalystvisionOS
static var savingError: UIDocument.State { get }
See Also
Constants
static var normal: UIDocument.State
The document is open, editing is enabled, and there are no conflicts or errors associated with it.
static var closed: UIDocument.State
There was an error in reading the document.
static var inConflict: UIDocument.State
Conflicts exist for the document file located at the file URL.
static var editingDisabled: UIDocument.State
The document is busy and it isn’t currently safe for user edits.
static var progressAvailable: UIDocument.State
The document is being downloaded or uploaded and progress information is available.
https://developer.apple.com/documentation/uikit/uidocument/handleerror(_:userinteractionpermitted:)
#app-main)
- UIKit
- UIDocument
- handleError(_:userInteractionPermitted:)
Instance Method
handleError(_:userInteractionPermitted:)
Handles an error that occurs during an attempt to read, save, or revert a document.
@MainActor func handleError( _ error: any Error, userInteractionPermitted: Bool )
Parameters
error
An object encapsulating information about an error encountered in an attempt to open, save, or revert a document. The error domain is NSCocoaErrorDomain. The error code is one of the enum constants declared in FoundationErrors.h.
userInteractionPermitted
If false, no attempt is (or should be) made to present a modal view to the user. This value can be false in cases such as when a save operation fails while the application is being suspended. If this parameter is true, UIKit or your override may present error information to the user in a modal view and (optionally) allow the user to resolve the error.
Discussion
Typical UIDocument subclasses don’t need to call or override this method. Instead, they can observe the stateChangedNotification notification to be notified of changes in document state. In their notification handler, they can check the value of the documentState property and proceed accordingly. See Resolve conflicts and handle errors for a discussion of this.
If you’re using managed documents (instances of the UIManagedDocument subclass), you must subclass this method and, if desired, the finishedHandlingError(_:recovered:) method. Subclassing allows your app to observe errors in saving or validation. The stateChangedNotification notification doesn’t contain a userInfo dictionary and so doesn’t convey specific error information.
If you directly call any of the advanced reading and writing methods that have an error-object parameter (for example, writeContents(_:andAttributes:safelyTo:for:)) and that call returns an NSError object by indirection, you should call this method ( handleError(_:userInteractionPermitted:)), passing in the error object.
This method is called by the default implementations of open(completionHandler:) and save(to:for:completionHandler:) when UIDocument encounters a reading or writing error, respectively.
If you override this method and don’t invoke the superclass implementation ( super), you’re responsible for the following:
-
Calling
finishedHandlingError(_:recovered:)when you’re finished handling the error — for example, when the application doesn’t require any additional user feedback about the error. -
Implementing
userInteractionNoLongerPermitted(forError:)to conclude error handling immediately. IfuserInteractionPermittedisfalse, you should immediately handle the error and callfinishedHandlingError(_:recovered:)within the context of thehandleError(_:userInteractionPermitted:).
See Also
Resolving conflicts and handling errors
func finishedHandlingError(any Error, recovered: Bool)
Tells UIKit that you finished handling the error.
func userInteractionNoLongerPermitted(forError: any Error)
Indicates when it’s no longer safe to proceed without immediately handling the error.
https://developer.apple.com/documentation/uikit/uidocument/read(from:)
#app-main)
- UIKit
- UIDocument
- read(from:)
Instance Method
read(from:)
Reads the document data in a file at a specified location in the application sandbox.
@MainActor func read(from url: URL) throws
Parameters
url
A file URL that identifies the location of the document file in the application sandbox. This file URL is typically the one returned by the fileURL property.
Discussion
Typical UIDocument subclasses shouldn’t need to call this method directly, especially if the entire file is read at once. The default implementation calls load(fromContents:ofType:) on the queue on which open(completionHandler:) was called to provide the UIDocument subclass with the document data object.
Subclasses that want more control over the reading of the document file—for example, that want to read a large document file incrementally—can override this method. It isn’t necessary for these subclasses to call the superclass implementation ( super).
See Also
Reading document data
Opens a document asynchronously.
func load(fromContents: Any, ofType: String?) throws
Loads the document data into the app’s data model.
https://developer.apple.com/documentation/uikit/uidocument/writecontents(_:to:for:originalcontentsurl:)
#app-main)
- UIKit
- UIDocument
- writeContents(_:to:for:originalContentsURL:)
Instance Method
writeContents(_:to:for:originalContentsURL:)
Writes the document data to disk at the sandbox location indicated by a file URL.
@MainActor func writeContents( _ contents: Any, to url: URL, for saveOperation: UIDocument.SaveOperation, originalContentsURL: URL? ) throws
Parameters
contents
The document data to write to disk. Typically, the data is encapsulated by an NSData object (if a flat file) or an FileWrapper object (if a file package).
If the object encapsulating the document data is of some other type, you should override this method or writeContents(_:andAttributes:safelyTo:for:) to perform the actual writing of the data.
url
A file URL specifying the location of the document file in the application sandbox.
saveOperation
A constant that indicates whether the document file is being written the first time or whether it is being overwritten. See UIDocument.SaveOperation for details.
originalContentsURL
A file URL specifying the previous location of the document file (if not nil).
Discussion
This method is called by the writeContents(_:andAttributes:safelyTo:for:) to write the actual file data. It is passed the contents object returned from your contents(forType:) implementation. The default implementation of this method supports NSData or FileWrapper contents by asking the contents object to save itself to the corresponding URL.
If you override this method, you may choose to return a different type of data from contents(forType:) or you may choose to not override contents(forType:) and generate the writable data directly within this method. If you override this method, you should not invoke the superclass implementation.
See Also
Writing document data
Asynchronously closes the document after saving any changes.
Returns the document data to be saved.
Saves document data to the specified location in the application sandbox.
Ensures that document data is written safely to a specified location in the application sandbox.
var savingFileType: String?
Returns the file type to use for saving a document.
Returns a dictionary of file attributes to associate with the document file when writing or updating it.
Returns a file extension to append to the file URL of the document file being written.
https://developer.apple.com/documentation/uikit/uidocument/writecontents(_:andattributes:safelyto:for:)
#app-main)
- UIKit
- UIDocument
- writeContents(_:andAttributes:safelyTo:for:)
Instance Method
writeContents(_:andAttributes:safelyTo:for:)
Ensures that document data is written safely to a specified location in the application sandbox.
@MainActor func writeContents( _ contents: Any, andAttributes additionalFileAttributes: [AnyHashable : Any]? = nil, safelyTo url: URL, for saveOperation: UIDocument.SaveOperation ) throws
Parameters
contents
The document data to write to disk. Typically, the data is encapsulated by an NSData object (if a flat file) or an FileWrapper object (if a file package).
If the object encapsulating the document data is of some other type, you should override this method or writeContents(_:to:for:originalContentsURL:) to perform the actual writing of the data.
additionalFileAttributes
A dictionary of FileManager file attributes to assign to the document file. The default implementation obtains these file attributes by calling fileAttributesToWrite(to:for:).
url
The file URL specifying the location of the document file in the application sandbox.
saveOperation
A constant that indicates whether the document file is being written the first time or whether it is being overwritten. See UIDocument.SaveOperation for details.
Discussion
This method is called by the save(to:for:completionHandler:) method to save the file data (and associated attributes in the case of an FileWrapper). It creates temporary files and directories as necessary so that successful saves can be completed atomically and failed saves can be rolled back cleanly. This method calls writeContents(_:to:for:originalContentsURL:) to save the contents object, passing the location for the new saved file in the toURL parameter and the location of the previously existing file in the originalContentsURL parameter, if this is an overwrite operation.
If you want to change how file data is saved, you generally override the writeContents(_:to:for:originalContentsURL:) method instead of this method. Additionally, you don’t need to call this method directly unless you are overriding the save(to:for:completionHandler:) method.
See Also
Writing document data
Asynchronously closes the document after saving any changes.
Returns the document data to be saved.
Saves document data to the specified location in the application sandbox.
func writeContents(Any, to: URL, for: UIDocument.SaveOperation, originalContentsURL: URL?) throws
Writes the document data to disk at the sandbox location indicated by a file URL.
var savingFileType: String?
Returns the file type to use for saving a document.
Returns a dictionary of file attributes to associate with the document file when writing or updating it.
Returns a file extension to append to the file URL of the document file being written.
https://developer.apple.com/documentation/uikit/uidocument/savingfiletype
- UIKit
- UIDocument
- savingFileType
Instance Property
savingFileType
Returns the file type to use for saving a document.
@MainActor var savingFileType: String? { get }
Return Value
A Uniform Type Identifier (UTI) identifying a document type (for example, PDF or HTML).
Discussion
The default implementation returns the current file type obtained from the fileType property. The default implementation of the save(to:for:completionHandler:) method appends an extension to the file URL that’s based on the file type. So if you want to move the document to a new type and extension, you can override this method to supply that file type.
See Also
Writing document data
Asynchronously closes the document after saving any changes.
Returns the document data to be saved.
Saves document data to the specified location in the application sandbox.
Ensures that document data is written safely to a specified location in the application sandbox.
func writeContents(Any, to: URL, for: UIDocument.SaveOperation, originalContentsURL: URL?) throws
Writes the document data to disk at the sandbox location indicated by a file URL.
Returns a dictionary of file attributes to associate with the document file when writing or updating it.
Returns a file extension to append to the file URL of the document file being written.
https://developer.apple.com/documentation/uikit/uinavigationitemrenamedelegate-96g5t
- UIKit
- UINavigationItemRenameDelegate
Protocol
UINavigationItemRenameDelegate
Methods an object implements to rename a navigation item.
Overview
A navigation item ( UINavigationItem) uses this delegate to determine whether a person can change the navigation item’s title and to handle the rename process.
Topics
Determining rename support
- navigationItemShouldBeginRenaming:
Asks the delegate whether the navigation item supports renaming.
- navigationItem:shouldEndRenamingWithTitle:
Asks the delegate whether to continue or abandon the rename process.
Handling the rename process
- navigationItem:willBeginRenamingWithSuggestedTitle:selectedRange:
Tells the delegate when the rename process starts.
- navigationItem:didEndRenamingWithTitle:
Tells the delegate when the rename process ends.
Relationships
Inherits From
NSObjectProtocol
Conforming Types
UIDocument
See Also
Renaming documents
renameDelegate
The delegate for renaming the navigation item.
https://developer.apple.com/documentation/uikit/uinavigationitem/renamedelegate-o32h
- UIKit
- UINavigationItem
- renameDelegate
Instance Property
renameDelegate
The delegate for renaming the navigation item.
Mentioned in
Building a desktop-class iPad app
Discussion
If you assign a non- nil value to this property, UIKit shows an inline text field UI for changing the navigation item’s title. This UI appears when either you or the system calls rename(_:) on the navigation controller, which occurs when a person taps Rename in the title menu or when you call rename(_:) explicitly.
To show Rename in the navigation item’s title menu, include the Rename menu element in the menu you return from titleMenuProvider. UIKit includes Rename in the set of menu element suggestions it passes in to this closure.
If you only want to show Rename in the title menu, assign a renameDelegate without setting a titleMenuProvider. In this case, UIKit automatically generates a title menu containing the Rename menu element only.
If you set this property to nil while a rename operation is in progress, the operation cancels immediately.
See Also
Renaming documents
UINavigationItemRenameDelegate
Methods an object implements to rename a navigation item.
https://developer.apple.com/documentation/uikit/uinavigationitemrenamedelegate-5j4ws/navigationitem(_:didendrenamingwith:)
#app-main)
- UIKit
- UINavigationItemRenameDelegate
- navigationItem(_:didEndRenamingWith:)
Instance Method
navigationItem(_:didEndRenamingWith:)
Tells the delegate when the rename process ends.
Mac CatalystvisionOS
@MainActor @preconcurrency func navigationItem( _: UINavigationItem, didEndRenamingWith title: String )
Required
Parameters
title
The new title of the navigation item.
Discussion
UIKit calls this method after a person finishes renaming the navigation item. Implement this method to update your data model with the new title as needed.
UIKit updates the navigation item’s title automatically. However, if you want to modify the final title that the system passes in to this method, you must update the navigation item’s title manually.
See Also
Handling the rename process
Tells the delegate when the rename process starts.
Required Default implementation provided.
https://developer.apple.com/documentation/uikit/uinavigationitemrenamedelegate-96g5t/navigationitem:didendrenamingwithtitle:
- UIKit
- UINavigationItemRenameDelegate
- navigationItem:didEndRenamingWithTitle:
Instance Method
navigationItem:didEndRenamingWithTitle:
Tells the delegate when the rename process ends.
- (void) navigationItem:(UINavigationItem *) navigationItem didEndRenamingWithTitle:(NSString *) title;
Parameters
navigationItem
The navigation item with the changing title.
title
The new title of the navigation item.
Discussion
UIKit calls this method after a person finishes renaming the navigation item. Implement this method to update your data model with the new title as needed.
UIKit updates the navigation item’s title automatically. However, if you want to modify the final title that the system passes in to this method, you must update the navigation item’s title manually.
See Also
Handling the rename process
- navigationItem:willBeginRenamingWithSuggestedTitle:selectedRange:
Tells the delegate when the rename process starts.
https://developer.apple.com/documentation/uikit/uidocument/filemodificationdate
- UIKit
- UIDocument
- fileModificationDate
Instance Property
fileModificationDate
The date and time your app last modified the document file.
@MainActor var fileModificationDate: Date? { get set }
Discussion
The modification date is updated by the open(completionHandler:), save(to:for:completionHandler:), and revert(toContentsOf:completionHandler:) methods. Its value is nil if none of these methods has completed successfully at least once. If you override any of these methods, you should be sure to set this property in your implementation.
UIKit sets this property before it calls the completion handlers of the open(completionHandler:), save(to:for:completionHandler:), and revert(toContentsOf:completionHandler:). If, outside of these methods or their completion handlers, you want to wait for any pending file operations to complete before you access this property, you can call performAsynchronousFileAccess(_:) and access the property value in the block parameter.
See Also
Accessing document attributes
var fileURL: URL
The file URL you use to initialize the document.
var localizedName: String
The localized name of the document.
var fileType: String?
The file type of the document.
var documentState: UIDocument.State
The current state of the document.
var progress: Progress?
The upload or download progress of a document.
https://developer.apple.com/documentation/uikit/uidocument/progress
https://developer.apple.com/documentation/uikit/uidocument/filenameextension(fortype:saveoperation:)
#app-main)
- UIKit
- UIDocument
- fileNameExtension(forType:saveOperation:)
Instance Method
fileNameExtension(forType:saveOperation:)
Returns a file extension to append to the file URL of the document file being written.
@MainActor func fileNameExtension( forType typeName: String?, saveOperation: UIDocument.SaveOperation
Parameters
typeName
A Uniform Type Identifier (UTI) that indicates the type of document (for example, PDF or HTML).
saveOperation
A constant that indicates whether the document file is being written the first time or whether it’s being overwritten. See UIDocument.SaveOperation for details.
Return Value
A string to use as the file extension of the document file.
Discussion
The default implementation queries Launch Services to obtain the file extension matching the file (document) type. You can override this method to return a file extension that’s different from the default extension. The default implementation of the save(to:for:completionHandler:) method calls this method before it gets the document content and writes the document file to disk.
See Also
Writing document data
Asynchronously closes the document after saving any changes.
Returns the document data to be saved.
Saves document data to the specified location in the application sandbox.
Ensures that document data is written safely to a specified location in the application sandbox.
func writeContents(Any, to: URL, for: UIDocument.SaveOperation, originalContentsURL: URL?) throws
Writes the document data to disk at the sandbox location indicated by a file URL.
var savingFileType: String?
Returns the file type to use for saving a document.
Returns a dictionary of file attributes to associate with the document file when writing or updating it.
https://developer.apple.com/documentation/uikit/uidocument/creationintent
https://developer.apple.com/documentation/uikit/uidocument/disableediting()
#app-main)
- UIKit
- UIDocument
- disableEditing()
Instance Method
disableEditing()
Disables editing when it’s unsafe to make changes to a document.
@MainActor func disableEditing()
Discussion
Subclasses should override this method to prevent the user from editing the document when it’s unsafe to do so, such as during a save-and-close or revert operation. When editing is safe again, UIKit class calls enableEditing(). The default implementation of this method does nothing.
See Also
Disabling and enabling editing
func enableEditing()
Enables editing when it’s safe again to make changes to a document.
https://developer.apple.com/documentation/uikit/uidocument/enableediting()
https://developer.apple.com/documentation/uikit/uidocument/changecounttoken(for:)
#app-main)
- UIKit
- UIDocument
- changeCountToken(for:)
Instance Method
changeCountToken(for:)
Returns a change token for a specific save operation.
@MainActor
Parameters
saveOperation
A constant that indicates whether the save operation is writing a new file or overwriting an existing one. See UIDocument.SaveOperation for descriptions of these constants.
Return Value
An object to use as a change-count token.
Discussion
To get autosaving capabilities for your documents, you must implement change tracking. Typically you do this by using an UndoManager object (assigned to undoManager property) to register changes or by calling the updateChangeCount(_:) method every time the user makes a change; UIKit then automatically determines whether there are unsaved changes and returns the proper value from hasUnsavedChanges. If you take neither of these approaches (and you want the autosaving feature), you must implement this method as well as updateChangeCount(withToken:for:) and hasUnsavedChanges.
You implement this particular method to return a change-count token that UIKit uses to encapsulate the history of document changes for a particular save operation. The token can be any object that represents the current change state of the document. This method is called at the start of the default implementation of the save(to:for:completionHandler:) method. At the end of this default implementation, it calls the updateChangeCount(withToken:for:) method, passing in the change-count token. You implement the latter method to compare the token with the one returned earlier; by doing so, you can determine if the document has acquired new unsaved changes between the start and end of an asynchronous write operation. You can then return the proper value from your override of hasUnsavedChanges.
See Also
Tracking changes and autosaving
var hasUnsavedChanges: Bool
A Boolean value that indicates whether the document has any unsaved changes.
func updateChangeCount(UIDocument.ChangeKind)
Updates the change counter by indicating the kind of change.
var undoManager: UndoManager!
The undo manager for the document.
func updateChangeCount(withToken: Any, for: UIDocument.SaveOperation)
Updates the change count with reference to a change-count token passed in by UIKit.
Initiates automatic saving of documents with unsaved changes.
https://developer.apple.com/documentation/uikit/uidocument/updatechangecount(withtoken:for:)
#app-main)
- UIKit
- UIDocument
- updateChangeCount(withToken:for:)
Instance Method
updateChangeCount(withToken:for:)
Updates the change count with reference to a change-count token passed in by UIKit.
@MainActor func updateChangeCount( withToken changeCountToken: Any, for saveOperation: UIDocument.SaveOperation )
Parameters
changeCountToken
An object to use as a change-count token. UIDocument obtained this token earlier by calling changeCountToken(for:).
saveOperation
A constant that indicates whether the save operation is writing a new file or overwriting an existing one. See UIDocument.SaveOperation for descriptions of these constants.
Discussion
To get autosaving capabilities for your documents, you must implement change tracking. Typically you do this by using an UndoManager object (assigned to undoManager property) to register changes or by calling the updateChangeCount(_:) method every time the user makes a change; UIKit then automatically determines whether there are unsaved changes and returns the proper value from hasUnsavedChanges. If you take neither of these approaches (and you want the autosaving feature), you must implement this method as well as changeCountToken(for:) and hasUnsavedChanges.
You implement the changeCountToken(for:) method to return a change-count token that UIKit uses to encapsulate the history of document changes for a particular save operation. The token can be any object that represents the current change state of the document. This method is called at the start of the default implementation of the save(to:for:completionHandler:) method. At the end of this default implementation, UIDocument calls this method ( updateChangeCount(withToken:for:)), passing in the change-count token. You implement this method to compare the token with the one returned earlier; by doing so, you can determine if the document has acquired new unsaved changes between the start and end of an asynchronous write operation. You can then return the proper value from your override of hasUnsavedChanges.
See Also
Tracking changes and autosaving
var hasUnsavedChanges: Bool
A Boolean value that indicates whether the document has any unsaved changes.
func updateChangeCount(UIDocument.ChangeKind)
Updates the change counter by indicating the kind of change.
var undoManager: UndoManager!
The undo manager for the document.
Returns a change token for a specific save operation.
Initiates automatic saving of documents with unsaved changes.
https://developer.apple.com/documentation/uikit/uidocument/autosave(completionhandler:)
#app-main)
- UIKit
- UIDocument
- autosave(completionHandler:)
Instance Method
autosave(completionHandler:)
Initiates automatic saving of documents with unsaved changes.
@MainActor
Parameters
completionHandler
A block with code to execute after automatic saving concludes. The block returns no value and has one parameter:
success
true if the autosaving operation succeeds, otherwise false.
The block is invoked on the calling queue.
Discussion
UIDocument periodically invokes this method to initiate a save operation if there are unsaved changes. You shouldn’t call this method directly. Subclasses can override it if they want to do special things with autosaving. The default implementation of this method invokes the hasUnsavedChanges method and, if that returns true, it invokes the save(to:for:completionHandler:) method.
This method should only be invoked for period-based saves. You may invoke it with the success parameter of the completion-handler parameter set to false and return; this makes it safe to not actually save when autosave(completionHandler:) is invoked. However, if you call save(to:for:completionHandler:), saving of document data must occur.
See Also
Tracking changes and autosaving
var hasUnsavedChanges: Bool
A Boolean value that indicates whether the document has any unsaved changes.
func updateChangeCount(UIDocument.ChangeKind)
Updates the change counter by indicating the kind of change.
var undoManager: UndoManager!
The undo manager for the document.
Returns a change token for a specific save operation.
func updateChangeCount(withToken: Any, for: UIDocument.SaveOperation)
Updates the change count with reference to a change-count token passed in by UIKit.
https://developer.apple.com/documentation/uikit/uidocument/useractivity
- UIKit
- UIDocument
- userActivity
Instance Property
userActivity
An object encapsulating a user activity supported by this document.
@MainActor var userActivity: NSUserActivity? { get set }
Discussion
UIDocument automatically creates NSUserActivity objects. The system makes user activities eligible for Handoff if the document is iCloud-based and the app’s Info.plist property list file includes a CFBundleDocumentTypes key of NSUbiquitousDocumentUserActivityType. The value of NSUbiquitousDocumentUserActivityType is a string that represents the NSUserActivity object’s activity type. The document’s URL is in the NSUserActivity object’s userInfo dictionary with the userActivityURLKey.
In iOS, to make an NSUserActivity object that UIKit manages current, you must either call becomeCurrent() explicitly or have the document’s NSUserActivity object also set on a UIViewController object that’s in the view hierarchy when the app comes to the foreground.
You can use this property from any thread. It’s KVO-observable in case you share the userActivity object with other objects that need to be kept in sync as the document moves into and out of iCloud.
See Also
Supporting user activities
func restoreUserActivityState(NSUserActivity)
Restores the state needed to continue the given user activity.
func updateUserActivityState(NSUserActivity)
Updates the state of the given user activity.
https://developer.apple.com/documentation/uikit/uidocument/restoreuseractivitystate(_:)
#app-main)
- UIKit
- UIDocument
- restoreUserActivityState(_:)
Instance Method
restoreUserActivityState(_:)
Restores the state needed to continue the given user activity.
@MainActor func restoreUserActivityState(_ userActivity: NSUserActivity)
Parameters
userActivity
The user activity to be continued.
Discussion
Subclasses override this method to restore the responder’s state with the given user activity. The override should use the state data contained in the userInfo dictionary of the given user activity to restore the object.
User activities managed by NSDocument can be restored automatically, if false is returned from application:continueActivity:restorationHandler: or if it’s unimplemented. In this situation, the document is opened by the NSDocumentController method openDocument(withContentsOf:display:completionHandler:) and receives a restoreUserActivityState(_:) message.
See Also
Supporting user activities
var userActivity: NSUserActivity?
An object encapsulating a user activity supported by this document.
func updateUserActivityState(NSUserActivity)
Updates the state of the given user activity.
https://developer.apple.com/documentation/uikit/uidocument/updateuseractivitystate(_:)
#app-main)
- UIKit
- UIDocument
- updateUserActivityState(_:)
Instance Method
updateUserActivityState(_:)
Updates the state of the given user activity.
@MainActor func updateUserActivityState(_ userActivity: NSUserActivity)
Parameters
userActivity
The user activity to be updated.
Discussion
The default implementation of this method puts the document’s fileURL into the NSUserActivity object’s userInfo dictionary with the userActivityURLKey. UIDocument automatically sets the needsSave property of the NSUserActivity object to true when the fileURL changes.
See Also
Supporting user activities
var userActivity: NSUserActivity?
An object encapsulating a user activity supported by this document.
func restoreUserActivityState(NSUserActivity)
Restores the state needed to continue the given user activity.
https://developer.apple.com/documentation/uikit/uidocument/finishedhandlingerror(_:recovered:)
#app-main)
- UIKit
- UIDocument
- finishedHandlingError(_:recovered:)
Instance Method
finishedHandlingError(_:recovered:)
Tells UIKit that you finished handling the error.
@MainActor func finishedHandlingError( _ error: any Error, recovered: Bool )
Parameters
error
An error object encapsulating information about the error.
recovered
true if you recovered from the error, otherwise false.
Discussion
This method is called by default when handling of an error (including any user interaction) is complete. Subclasses need to call this method only if they override handleError(_:userInteractionPermitted:) and do not call the superclass implementation ( super). If you override this method, you must call super.
See Also
Resolving conflicts and handling errors
func handleError(any Error, userInteractionPermitted: Bool)
Handles an error that occurs during an attempt to read, save, or revert a document.
func userInteractionNoLongerPermitted(forError: any Error)
Indicates when it’s no longer safe to proceed without immediately handling the error.
https://developer.apple.com/documentation/uikit/uidocument/userinteractionnolongerpermitted(forerror:)
#app-main)
- UIKit
- UIDocument
- userInteractionNoLongerPermitted(forError:)
Instance Method
userInteractionNoLongerPermitted(forError:)
Indicates when it’s no longer safe to proceed without immediately handling the error.
@MainActor func userInteractionNoLongerPermitted(forError error: any Error)
Parameters
error
An error object encapsulating information about the error.
Discussion
UIKit calls this method when it’s no longer safe to proceed without immediately handling the error, such as when the application is being suspended. Subclasses that override this method must immediately end error handling (including dismissing any interactive user interface) and call finishedHandlingError(_:recovered:) before returning. It’s only necessary to override this method if you override handleError(_:userInteractionPermitted:) without invoking the superclass implementation ( super).
See Also
Resolving conflicts and handling errors
func handleError(any Error, userInteractionPermitted: Bool)
Handles an error that occurs during an attempt to read, save, or revert a document.
func finishedHandlingError(any Error, recovered: Bool)
Tells UIKit that you finished handling the error.
https://developer.apple.com/documentation/uikit/uidocument/changekind
https://developer.apple.com/documentation/uikit/uidocument/saveoperation
https://developer.apple.com/documentation/uikit/uidocument/state
- UIKit
- UIDocument
- UIDocument.State
Structure
UIDocument.State
Constants that specify the document state.
iOSiPadOSMac CatalystvisionOS
struct State
Overview
A UIDocument object stores the current state of the document in the documentState property. To receive notifications about changes in document state, observe the stateChangedNotification notification.
Topics
Constants
static var normal: UIDocument.State
The document is open, editing is enabled, and there are no conflicts or errors associated with it.
static var closed: UIDocument.State
There was an error in reading the document.
static var inConflict: UIDocument.State
Conflicts exist for the document file located at the file URL.
static var savingError: UIDocument.State
There was an error in saving or reverting the document.
static var editingDisabled: UIDocument.State
The document is busy and it isn’t currently safe for user edits.
static var progressAvailable: UIDocument.State
The document is being downloaded or uploaded and progress information is available.
Initializers
init(rawValue: UInt)
Creates a document state structure with the specified raw value.
Relationships
Conforms To
BitwiseCopyableEquatableExpressibleByArrayLiteralOptionSetRawRepresentableSendableSendableMetatypeSetAlgebra
See Also
Constants
enum ChangeKind
Constants that specify the kind of change to a document.
enum SaveOperation
Constants that specify the type of save operation.
class let userActivityURLKey: String
The key that identifies the document associated with a user activity.
https://developer.apple.com/documentation/uikit/uidocument/useractivityurlkey
- UIKit
- UIDocument
- userActivityURLKey
Type Property
userActivityURLKey
The key that identifies the document associated with a user activity.
class let userActivityURLKey: String
Discussion
You use this key in the userInfo dictionary of an NSUserActivity object. Its value is the URL of the document associated with the user activity.
When the NSUbiquitousDocumentUserActivityType key is present in a CFBundleDocumentTypes entry, AppKit automatically creates an NSUserActivity object for documents in iCloud, using the given activity type.
See Also
Constants
enum ChangeKind
Constants that specify the kind of change to a document.
enum SaveOperation
Constants that specify the type of save operation.
struct State
Constants that specify the document state.
https://developer.apple.com/documentation/uikit/uidocument/statechangedmessage
- UIKit
- UIDocument
- UIDocument.StateChangedMessage Beta
Structure
UIDocument.StateChangedMessage
struct StateChangedMessage
Topics
Initializers
init(document: UIDocument)
Instance Properties
var document: UIDocument
Relationships
Conforms To
NotificationCenter.MainActorMessageNotificationCenter.Message
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/customizing-a-document-based-app-s-launch-experience)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocumentbrowserviewcontroller)
https://developer.apple.com/documentation/uikit/uidocument/init(fileurl:)),
https://developer.apple.com/documentation/uikit/uidocument/filetype)
https://developer.apple.com/documentation/uikit/uidocument/localizedname)
https://developer.apple.com/documentation/uikit/uidocument/save(to:for:completionhandler:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument/open(completionhandler:))
https://developer.apple.com/documentation/uikit/uidocument/close(completionhandler:))
https://developer.apple.com/documentation/uikit/uidocument/open(completionhandler:)),
https://developer.apple.com/documentation/uikit/uidocument/close(completionhandler:)),
),#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument)-based
https://developer.apple.com/documentation/uikit/uidocument):
https://developer.apple.com/documentation/uikit/uidocument/performasynchronousfileaccess(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument/revert(tocontentsof:completionhandler:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument/fileurl)
https://developer.apple.com/documentation/uikit/uidocument/fileurl))
https://developer.apple.com/documentation/uikit/uidocument/contents(fortype:))
https://developer.apple.com/documentation/uikit/uidocument/load(fromcontents:oftype:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument),
https://developer.apple.com/documentation/uikit/uidocument/hasunsavedchanges)
https://developer.apple.com/documentation/uikit/uidocument/undomanager)
https://developer.apple.com/documentation/uikit/uidocument/updatechangecount(_:))
https://developer.apple.com/documentation/uikit/uidocument/documentstate)
https://developer.apple.com/documentation/uikit/uidocument/statechangednotification)
https://developer.apple.com/documentation/uikit/uidocument/state/inconflict).
https://developer.apple.com/documentation/uikit/uidocument/state/closed)
https://developer.apple.com/documentation/uikit/uidocument/state/savingerror)
https://developer.apple.com/documentation/uikit/uidocument/revert(tocontentsof:completionhandler:)),
),#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument/handleerror(_:userinteractionpermitted:))
https://developer.apple.com/documentation/uikit/uidocument/contents(fortype:)).
https://developer.apple.com/documentation/uikit/uidocument/read(from:))
https://developer.apple.com/documentation/uikit/uidocument/writecontents(_:to:for:originalcontentsurl:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument/save(to:for:completionhandler:)).
).#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument/writecontents(_:andattributes:safelyto:for:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument/savingfiletype)
https://developer.apple.com/documentation/uikit/uidocument/filetype)).
https://developer.apple.com/documentation/uikit/uinavigationitemrenamedelegate-96g5t)
https://developer.apple.com/documentation/uikit/uidocumentviewcontroller),
https://developer.apple.com/documentation/uikit/uinavigationitem/renamedelegate-o32h).
.#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uinavigationitemrenamedelegate-5j4ws/navigationitem(_:didendrenamingwith:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uinavigationitemrenamedelegate-96g5t/navigationitem:didendrenamingwithtitle:)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument/init(fileurl:))
https://developer.apple.com/documentation/uikit/uidocument/filemodificationdate)
https://developer.apple.com/documentation/uikit/uidocument/progress)
https://developer.apple.com/documentation/uikit/uidocument/fileattributestowrite(to:for:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument/filenameextension(fortype:saveoperation:))
https://developer.apple.com/documentation/uikit/uidocument/creationintent)
https://developer.apple.com/documentation/uikit/uidocument/disableediting())
https://developer.apple.com/documentation/uikit/uidocument/enableediting())
https://developer.apple.com/documentation/uikit/uidocument/changecounttoken(for:))
https://developer.apple.com/documentation/uikit/uidocument/updatechangecount(withtoken:for:))
https://developer.apple.com/documentation/uikit/uidocument/autosave(completionhandler:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument/useractivity)
https://developer.apple.com/documentation/uikit/uidocument/restoreuseractivitystate(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument/updateuseractivitystate(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument/finishedhandlingerror(_:recovered:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument/userinteractionnolongerpermitted(forerror:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uidocument/changekind)
https://developer.apple.com/documentation/uikit/uidocument/saveoperation)
https://developer.apple.com/documentation/uikit/uidocument/state)
https://developer.apple.com/documentation/uikit/uidocument/useractivityurlkey)
https://developer.apple.com/documentation/uikit/uidocument/statechangedmessage)
https://developer.apple.com/documentation/uikit/using-responders-and-the-responder-chain-to-handle-events
- UIKit
- Touches, presses, and gestures
- Using responders and the responder chain to handle events
Article
Using responders and the responder chain to handle events
Learn how to handle events that propagate through your app.
Overview
Apps receive and handle events using responder objects. A responder object is any instance of the UIResponder class, and common subclasses include UIView, UIViewController, and UIApplication. Responders receive the raw event data and must either handle the event or forward it to another responder object. When your app receives an event, UIKit automatically directs that event to the most appropriate responder object, known as the first responder.
Unhandled events are passed from responder to responder in the active responder chain, which is the dynamic configuration of your app’s responder objects. The following image shows the responders in an app whose interface contains a label, a text field, a button, and two background views. The diagram also shows how events move from one responder to the next, following the responder chain.
If the text field doesn’t handle an event, UIKit sends the event to the text field’s parent UIView object, followed by the root view of the window. From the root view, the responder chain diverts to the owning view controller before directing the event to the window. If the window can’t handle the event, UIKit delivers the event to the UIApplication object, and possibly to the app delegate if that object is an instance of UIResponder and not already part of the responder chain.
Determine an event’s first responder
UIKit designates an object as the first responder to an event based on the type of that event. Event types include:
| Event type | First responder |
|---|---|
| Touch events | The view in which the touch occurred. |
| Press events | The object that has focus. |
| Shake-motion events | The object that you (or UIKit) designate. |
| Remote-control events | The object that you (or UIKit) designate. |
| Editing menu messages | The object that you (or UIKit) designate. |
Controls communicate directly with their associated target object using action messages. When the user interacts with a control, the control sends an action message to its target object. Action messages aren’t events, but they may still take advantage of the responder chain. When the target object of a control is nil, UIKit starts from the target object and traverses the responder chain until it finds an object that implements the appropriate action method. For example, the UIKit editing menu uses this behavior to search for responder objects that implement methods with names like cut(_:), copy(_:), or paste(_:).
Gesture recognizers receive touch and press events before their view does. If a view’s gesture recognizers fail to recognize a sequence of touches, UIKit sends the touches to the view. If the view doesn’t handle the touches, UIKit passes them up the responder chain. For more information about using gesture recognizer’s to handle events, see Handling UIKit gestures.
Determine which responder contained a touch event
UIKit uses view-based hit-testing to determine where touch events occur. Specifically, UIKit compares the touch location to the bounds of view objects in the view hierarchy. The hitTest(_:with:) method of UIView traverses the view hierarchy, looking for the deepest subview that contains the specified touch, which becomes the first responder for the touch event.
When a touch occurs, UIKit creates a UITouch object and associates it with a view. As the touch location or other parameters change, UIKit updates the same UITouch object with the new information. The only property that doesn’t change is the view. (Even when the touch location moves outside the original view, the value in the touch’s view property doesn’t change). When the touch ends, UIKit releases the UITouch object.
Alter the responder chain
You can alter the responder chain by overriding the next property of your responder objects. When you do this, the next responder is the object that you return.
Many UIKit classes already override this property and return specific objects, including:
-
UIViewobjects. If the view is the root view of a view controller, the next responder is the view controller; otherwise, the next responder is the view’s superview. -
UIViewControllerobjects. -
If the view controller’s view is the root view of a window, the next responder is the window object.
-
If the view controller was presented by another view controller, the next responder is the presenting view controller.
-
UIWindowobjects. The window’s next responder is theUIApplicationobject. -
UIApplicationobject. The next responder is the app delegate, but only if the app delegate is an instance ofUIResponderand isn’t a view, view controller, or the app object itself.
See Also
Essentials
class UIResponder
An abstract interface for responding to and handling events.
class UIEvent
An object that describes a single user interaction with your app.
https://developer.apple.com/documentation/uikit/about-the-app-launch-sequence
- UIKit
- App and environment
- Responding to the launch of your app
- About the app launch sequence
Article
About the app launch sequence
Learn the order in which the system executes your code at app launch time.
Overview
An app launch involves a complex sequence of steps, most of which the system handles automatically. During the launch sequence, UIKit calls methods in your app delegate and scene delegate so you can prepare your app for user interaction and perform any tasks specific to your app’s requirements. The following illustrates the individual steps of this launch sequence, from when the user or system launches your app to when the sequence completes:
-
The system executes the
main()function that Xcode provides in an Objective-C project, or that’s available when you use@mainin a Swift project. -
The
main()function callsUIApplicationMain(_:_:_:_:), which creates an instance ofUIApplicationand your app delegate. -
UIKit calls the
application(_:willFinishLaunchingWithOptions:)method in your app delegate. -
UIKit performs view controller state restoration, which results in the execution of additional methods in your app delegate and app’s view controllers. For more information, see About the UI restoration process.
-
UIKit calls your app delegate’s
application(_:didFinishLaunchingWithOptions:)method. -
After the app launch completes, UIKit prepares a scene to connect to your app, and then calls
scene(_:willConnectTo:options:). UIKit may deliver a user activity to this method for you to handle during scene connection.
After the launch sequence completes, the system displays your app’s user interface and informs your app or scene delegates when life-cycle events occur.
Prepare your app for prewarming
In iOS 15 and later, the system may, depending on device conditions, prewarm your app — launch nonrunning application processes to reduce the amount of time the user waits before the app is usable. Prewarming executes an app’s launch sequence up until, but not including, when main() calls UIApplicationMain(_:_:_:_:). This provides the system with an opportunity to build and cache any low-level structures it requires in anticipation of a full launch.
After the system prewarms your app, its launch sequence remains in a paused state until the app launches and the sequence resumes, or the system removes the prewarmed app from memory to reclaim resources. The system can prewarm your app after a device reboot, and periodically as system conditions allow.
If your app executes code before the call to UIApplicationMain(_:_:_:_:), such as in static initializers like load(), don’t make assumptions about what services and resources are available. For example, keychain items may be unavailable because their data protection policies require an unlocked device and prewarming happens even when the device is in a locked state. If your code is dependent upon access to a specific service or resource, migrate that code to a later part of the launch sequence.
Prewarming an app results in an indeterminate amount of time between when the prewarming phase completes and when the user, or system, fully launches the app. Because of this, use MetricKit to accurately measure user-driven launch and resume times instead of manually signposting various points of the launch sequence.
See Also
Launch time
Performing one-time setup for your app
Ensure proper configuration of your app environment.
Return your app to its previous state after the system terminates it.
https://developer.apple.com/documentation/uikit/about-the-ui-preservation-process
- UIKit
- View controllers
- Preserving your app’s UI across launches
- About the UI preservation process
Article
About the UI preservation process
Learn how to customize the UIKit state preservation process.
Overview
The following diagram shows the sequence of calls that happens during the interface preservation process. After asking your app delegate if you want your app state to be preserved, UIKit encodes the objects currently in your app’s view controller hierarchy. Only view controllers with a valid restorationIdentifier are preserved.
The preservation process walks your view controller hierarchy and recursively encodes the objects that it finds. The process starts with the root view controllers of your app’s windows, which write their data to the provided archive. If the root view controller’s data includes references to other view controllers, UIKit asks each new view controller to encode its data in a separate portion of the archive. Those child view controllers may then encode their own children, and so on.
UIKit view controllers automatically encode their child view controllers, as appropriate. If you define a custom container view controller, your view controller’s encodeRestorableState(with:) method must similarly write any child view controllers to the provided archive.
Exclude view controllers from preservation
There are two ways to exclude a view controller (and its views) from the state restoration process:
-
Set its
restorationIdentifierproperty tonil. -
Provide a restoration class and return
nilfrom theviewController(withRestorationIdentifierPath:coder:)method.
Excluding a view controller prevents that view controller from being saved in the archive. It also excludes all of the view controller’s children from being preserved.
Encode any object in your app
State restoration isn’t limited to your app’s views and view controllers. Any object that adopts the UIStateRestoring protocol can also be included in the restoration archive. For example, you might adopt this protocol in an object that stores global configuration data for your app. To add an object like this to the archive:
-
Register the object while your app is running by calling the
registerObject(forStateRestoration:restorationIdentifier:)method ofUIApplication. For example, you might register a configuration object immediately after creating it. -
In one of your
encodeRestorableState(with:)methods, encode the object into the restoration archive. You can also encode it in your app delegate’sapplication(_:willEncodeRestorableStateWith:)method.
You can encode any data you want for your custom objects, as long as it’s sufficient to return that object to its previous state during the next launch cycle. Encode data that isn’t crucial to your app’s behavior, and never encode data that should be persisted in other ways. For example, don’t encode your app’s settings or user data that must persist between launch cycles.
See Also
Process details
About the UI restoration process
Learn how to customize the UIKit state restoration process.
https://developer.apple.com/documentation/uikit/uiapplication/shared
https://developer.apple.com/documentation/uikit/uiwindow
- UIKit
- UIWindow
Class
UIWindow
The backdrop for your app’s user interface and the object that dispatches events to your views.
tvOS
@MainActor class UIWindow
Mentioned in
Using responders and the responder chain to handle events
Overview
Windows work with your view controllers to handle events and to perform many other tasks that are fundamental to your app’s operation. UIKit handles most window-related interactions, working with other objects as needed to implement many app behaviors.
You use windows only when you need to do the following:
-
Provide a main window to display your app’s content.
-
Create additional windows (as needed) to display additional content.
Normally, Xcode provides your app’s main window. New iOS projects use storyboards to define the app’s views. Storyboards require the presence of a window property on the app delegate object, which the Xcode templates automatically provide. If your app doesn’t use storyboards, you must create this window yourself.
Most apps need only one window, which displays the app’s content on the device’s main screen. Although you can create additional windows on the device’s main screen, extra windows are commonly used to display content on an external screen, as described in Presenting content on a connected display.
You also use UIWindow objects for a handful of other tasks:
-
Setting the z-axis level of your window, which affects the visibility of the window relative to other windows.
-
Showing windows and making them the target of keyboard events.
-
Converting coordinate values to and from the window’s coordinate system.
-
Changing the root view controller of a window.
-
Changing the screen on which the window is displayed.
Windows don’t have any visual appearance of their own. Instead, a window hosts one or more views, which are managed by the window’s root view controller. You configure the root view controller in your storyboards, adding whatever views are appropriate for your interface.
You should rarely need to subclass UIWindow. The kinds of behaviors you might implement in a window can usually be implemented in a higher-level view controller more easily. One of the few times you might want to subclass is to override the becomeKey() or resignKey() methods to implement custom behaviors when a window’s key status changes. For information about how to display a window on a specific screen, see UIScreen.
Understand keyboard interactions
Whereas touch events are delivered to the window where they occurred, events that don’t have a relevant coordinate value are delivered to the key window. Only one window at a time can be the key window, and you can use a window’s isKeyWindow property to determine its status. Most of the time, your app’s main window is the key window, but UIKit may designate a different window as needed.
If you need to know which window is key, observe the didBecomeKeyNotification and didResignKeyNotification notifications. The system sends those notifications on the main actor in response to key window changes in your app. To force a window become key, or to force a window to resign the key status, call the appropriate methods of this class.
Topics
Creating a window
init(windowScene: UIWindowScene)
Creates a window and associates it with the specified scene object.
Configuring the window
var rootViewController: UIViewController?
The root view controller for the window.
var windowLevel: UIWindow.Level
The position of the window in the z-axis.
struct Level
The positioning of windows relative to each other.
var canResizeToFitContent: Bool
A Boolean value that indicates whether the window’s constraint-based content determines its size.
var screen: UIScreen
The screen to display the window on.
Deprecated
Making windows key
var isKeyWindow: Bool
A Boolean value that indicates whether the window is the key window.
var canBecomeKey: Bool
A Boolean value that indicates whether the window can become the key window.
func makeKeyAndVisible()
Shows the window and makes it the key window.
func makeKey()
Makes the window the key window.
func becomeKey()
Tells the window that it’s the key window.
func resignKey()
Tells the window that it’s no longer the key window.
Getting related objects
var windowScene: UIWindowScene?
The scene containing the window.
var avDisplayManager: AVDisplayManager
The display manager that handles requests for screen resolution, refresh rate, and HDR mode information.
Converting coordinates
Converts a point from the current window’s coordinate system to the coordinate system of another window.
Converts a point from the coordinate system of a given window to the coordinate system of the current window.
Converts a rectangle from the current window’s coordinate system to the coordinate system of another window.
Converts a rectangle from the coordinate system of another window to coordinate system of the current window.
Sending events
func sendEvent(UIEvent)
Dispatches the specified event to its views.
Responding to window-related notifications
class let didBecomeVisibleNotification: NSNotification.Name
A notification that posts when a window becomes visible.
class let didBecomeHiddenNotification: NSNotification.Name
A notification that posts when a window becomes hidden.
class let didBecomeKeyNotification: NSNotification.Name
A notification that posts whenever a window becomes the key window.
class let didResignKeyNotification: NSNotification.Name
A notification that posts whenever a window resigns its status as main window.
Responding to keyboard notifications
class let keyboardWillShowNotification: NSNotification.Name
A notification that posts immediately prior to displaying the keyboard.
class let keyboardDidShowNotification: NSNotification.Name
A notification that posts immediately after displaying the keyboard.
class let keyboardWillHideNotification: NSNotification.Name
A notification that posts immediately prior to dismissing the keyboard.
class let keyboardDidHideNotification: NSNotification.Name
A notification that posts immediately after dismissing the keyboard.
class let keyboardWillChangeFrameNotification: NSNotification.Name
A notification that posts immediately prior to a change in the keyboard’s frame.
class let keyboardDidChangeFrameNotification: NSNotification.Name
A notification that posts immediately after a change in the keyboard’s frame.
class let keyboardAnimationCurveUserInfoKey: String
A user info key to retrieve the animation curve that the system uses to animate the keyboard onto or off the screen.
class let keyboardAnimationDurationUserInfoKey: String
A user info key to retrieve the duration of the keyboard animation in seconds.
class let keyboardIsLocalUserInfoKey: String
A user info key to retrieve a Boolean value that indicates whether the keyboard belongs to the current app.
class let keyboardFrameBeginUserInfoKey: String
A user info key to retrieve the keyboard’s frame at the beginning of its animation.
class let keyboardFrameEndUserInfoKey: String
A user info key to retrieve the keyboard’s frame at the end of its animation.
Working with layout guides
var safeAreaAspectFitLayoutGuide: any UILayoutGuide & UILayoutGuideAspectFitting
A layout guide for placing content of a particular aspect ratio.
protocol UILayoutGuideAspectFitting
The interface for a layout guide that supports a particular aspect ratio.
Structures
struct DidBecomeHiddenMessage Beta
struct DidBecomeKeyMessage Beta
struct DidBecomeVisibleMessage Beta
struct DidResignKeyMessage Beta
Initializers
convenience init() Deprecated
init(frame: CGRect) Deprecated
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Windows
protocol UICoordinateSpace
A set of methods for converting between different frames of reference on a screen.
https://developer.apple.com/documentation/uikit/uiapplication/open(_:options:completionhandler:)
#app-main)
- UIKit
- UIApplication
- open(_:options:completionHandler:)
Instance Method
open(_:options:completionHandler:)
Attempts to asynchronously open the resource at the specified URL.
@MainActor func open( _ url: URL, options: [UIApplication.OpenExternalURLOptionsKey : Any] = [:],
) @MainActor func open( _ url: URL, options: [UIApplication.OpenExternalURLOptionsKey : Any] = [:]
Parameters
url
A URL (Universal Resource Locator). The resource identified by this URL may be local to the current app or it may be one that must be provided by a different app. UIKit supports many common schemes, including the http, https, tel, facetime, and mailto schemes. You can also employ custom URL schemes associated with apps installed on the device.
options
A dictionary of options to use when opening the URL. For a list of possible keys to include in this dictionary, see UIApplication.OpenExternalURLOptionsKey.
completion
The block to execute with the results. Provide a value for this parameter if you want to be informed of the success or failure of opening the URL. This block is executed asynchronously on your app’s main thread. The block has no return value and takes the following parameter:
success
A Boolean value that indicates whether the URL was opened successfully.
Discussion
Use this method to open the specified resource. If the specified URL scheme is handled by another app, iOS launches that app and passes the URL to it. (Launching the app brings the other app to the foreground.) If no app is capable of handling the specified scheme, the completion handler is called with the success parameter set to false.
To determine whether an app is installed that is capable of handling the URL, call the canOpenURL(_:) method before calling this one. Be sure to read the description of that method for an important note about registering the schemes you want to employ.
See Also
Opening a URL resource
Returns a Boolean value that indicates whether an app is available to handle a URL scheme.
struct OpenExternalURLOptionsKey
Options for opening a URL.
https://developer.apple.com/documentation/uikit/uiapplication/beginignoringinteractionevents()
#app-main)
- UIKit
- UIApplication
- beginIgnoringInteractionEvents() Deprecated
Instance Method
beginIgnoringInteractionEvents()
Tells the receiver to suspend the handling of touch-related events.
iOS 2.0–13.0DeprecatediPadOS 2.0–13.0DeprecatedMac Catalyst 13.1–13.1DeprecatedtvOSDeprecated
@MainActor func beginIgnoringInteractionEvents()
Discussion
You typically call this method before starting an animation or transition. Calls are nested with the endIgnoringInteractionEvents() method.
See Also
Deprecated methods
Asks the system to activate an existing scene, or create a new scene and associate it with your app.
Deprecated
func endIgnoringInteractionEvents()
Tells the receiver to resume the handling of touch-related events.
func setMinimumBackgroundFetchInterval(TimeInterval)
Specifies the minimum amount of time that must elapse between background fetch operations.
func scheduleLocalNotification(UILocalNotification)
Schedules a local notification for delivery at its encapsulated date and time.
func presentLocalNotificationNow(UILocalNotification)
Presents a local notification immediately.
func cancelLocalNotification(UILocalNotification)
Cancels the delivery of the specified scheduled local notification.
func cancelAllLocalNotifications()
Cancels the delivery of all scheduled local notifications.
Configures a periodic handler for VoIP apps in older versions of iOS.
let UIMinimumKeepAliveTimeout: TimeInterval
The minimum amount of time (measured in seconds) an app may run a critical background task in the background.
func clearKeepAliveTimeout()
Removes a previously installed periodic handler block.
func setStatusBarHidden(Bool, with: UIStatusBarAnimation)
Hides or shows the status bar, optionally animating the transition.
func setStatusBarStyle(UIStatusBarStyle, animated: Bool)
Sets the style of the status bar, optionally animating the transition to the new style.
func setStatusBarOrientation(UIInterfaceOrientation, animated: Bool)
Sets the app’s status bar to the specified orientation, optionally animating the transition.
func registerUserNotificationSettings(UIUserNotificationSettings)
Registers your preferred options for notifying the user.
func registerForRemoteNotifications(matching: UIRemoteNotificationType)
Register to receive remote notifications of the specified types via Apple Push Notification service.
https://developer.apple.com/documentation/uikit/uiapplication/registerforremotenotifications()
#app-main)
- UIKit
- UIApplication
- registerForRemoteNotifications()
Instance Method
registerForRemoteNotifications()
Registers to receive remote notifications through Apple Push Notification service.
tvOS
@MainActor func registerForRemoteNotifications()
Discussion
Call this method to initiate the registration process with Apple Push Notification service. If registration succeeds, the app calls your app delegate object’s application(_:didRegisterForRemoteNotificationsWithDeviceToken:) method and passes it a device token. You should pass this token along to the server you use to generate remote notifications for the device. If registration fails, the app calls its app delegate’s application(_:didFailToRegisterForRemoteNotificationsWithError:) method instead.
If you want your app’s remote notifications to display alerts, play sounds, or perform other user-facing actions, you must request authorization to do so using the requestAuthorization(options:completionHandler:) method of UNUserNotificationCenter. If you do not request and receive authorization for your app’s interactions, the system delivers all remote notifications to your app silently.
See Also
Registering for remote notifications
func unregisterForRemoteNotifications()
Unregisters for all remote notifications received through Apple Push Notification service.
var isRegisteredForRemoteNotifications: Bool
A Boolean value that indicates whether the app is currently registered for remote notifications.
https://developer.apple.com/documentation/uikit/uiapplication/applicationsupportsshaketoedit
- UIKit
- UIApplication
- applicationSupportsShakeToEdit
Instance Property
applicationSupportsShakeToEdit
A Boolean value that determines whether shaking the device displays the undo-redo user interface.
@MainActor var applicationSupportsShakeToEdit: Bool { get set }
Discussion
The default value is true. Set the property to false if you don’t want your app to display the Undo and Redo buttons when users shake the device.
See Also
Controlling and handling events
func sendEvent(UIEvent)
Dispatches an event to the appropriate responder objects in the app.
Sends an action message identified by the selector to a specified target.
https://developer.apple.com/documentation/uikit/uiapplication/canopenurl(_:)
#app-main)
- UIKit
- UIApplication
- canOpenURL(_:)
Instance Method
canOpenURL(_:)
Returns a Boolean value that indicates whether an app is available to handle a URL scheme.
tvOS
nonisolated
Parameters
url
A URL (Universal Resource Locator). At runtime, the system determines if the device has an installed app registered to handle the URL’s scheme. The device can have more than one app registered to handle a scheme.
The URL can have a common scheme such as http, https, tel, or facetime, or a custom scheme. For information about supported schemes, see Apple URL Scheme Reference.
Return Value
false if the device doesn’t have an installed app registered to handle the URL’s scheme, or if you haven’t declared the URL’s scheme in your Info.plist file; otherwise, true.
Discussion
When this method returns true, iOS guarantees subsequent calls to the open(_:options:completionHandler:) method with the same URL will successfully launch an app that can handle the URL. The return value doesn’t indicate the validity of the URL, whether the specified resource exists, or, in the case of a universal link, whether the device has an installed app registered to respond to the universal link.
You can call this method safely on a thread that isn’t the main thread.
If you link your app against an earlier version of iOS but it is running in iOS 9.0 or later, you can call this method up to 50 times. After reaching that limit, subsequent calls always return false. If the user reinstalls or upgrades the app, iOS resets the limit.
Unlike this method, the open(_:options:completionHandler:) method isn’t constrained by the LSApplicationQueriesSchemes requirement. If an app is available to handle the URL, the system will launch it, even if you haven’t declared the scheme.
Using universal links instead of custom URL schemes removes the need to use this method to validate target links; if no app is available to handle a universal link, iOS routes it to the person’s default browser, allowing the associated website to respond. For more information on universal links, see Allowing apps and websites to link to your content.
See Also
Related Documentation
Attempts to open the resource at the specified URL.
Deprecated
Opening a URL resource
Attempts to asynchronously open the resource at the specified URL.
struct OpenExternalURLOptionsKey
Options for opening a URL.
https://developer.apple.com/documentation/uikit/uiapplication/beginbackgroundtask(expirationhandler:)
#app-main)
- UIKit
- UIApplication
- beginBackgroundTask(expirationHandler:)
Instance Method
beginBackgroundTask(expirationHandler:)
Marks the start of a task that should continue if the app enters the background.
tvOS
tvOS, visionOS
nonisolated
iOS, iPadOS, Mac Catalyst
Parameters
handler
A handler to be called shortly before the app’s remaining background time reaches 0. Use this handler to clean up and mark the end of the background task. Failure to end the task explicitly will result in the termination of the app. The system calls the handler synchronously on the main thread, blocking the app’s suspension momentarily.
Return Value
A unique identifier for the new background task. You must pass this value to the endBackgroundTask(_:) method to mark the end of this task. This method returns invalid if running in the background isn’t possible.
Discussion
This method requests additional background execution time for your app. Call this method when leaving a task unfinished might be detrimental to your app’s user experience. For example, call this method before writing data to a file to prevent the system from suspending your app while the operation is in progress. For background tasks requiring more time, use Background Tasks.
Call this method as early as possible before starting your task, preferably before your app actually enters the background. The method requests the task assertion for your app asynchronously. If you call this method shortly before your app is due to be suspended, there’s a chance that the system might suspend your app before that task assertion is granted. For example, don’t call this method at the very end of your applicationDidEnterBackground(_:) method and expect your app to continue running. If the system is unable to grant the task assertion, it calls your expiration handler.
Each call to this method must be balanced by a matching call to the endBackgroundTask(_:) method. Apps running background tasks have a finite amount of time in which to run them. (You can find out the maximum background time available using the backgroundTimeRemaining property.) If you don’t call endBackgroundTask(_:) for each task before time expires, the system kills the app. If you provide a block object in the handler parameter, the system calls your handler before time expires to give you a chance to end the task.
You can call this method at any point in your app’s execution. You may also call this method multiple times to mark the beginning of several background tasks that run in parallel. However, each task must be ended separately. You identify a given task using the value returned by this method.
To assist with debugging, this method generates a name for the task, based on the name of the calling method or function. If you want to specify a custom name, use the beginBackgroundTask(withName:expirationHandler:) method instead.
This method can be safely called on a non-main thread. To extend the execution time of an app extension, use the performExpiringActivity(withReason:using:) method of ProcessInfo instead.
See Also
Related Documentation
Background Tasks
Support background processing in your app by wrapping your app’s most critical work in framework-provided tasks.
Managing background tasks
var backgroundRefreshStatus: UIBackgroundRefreshStatus
Indicates whether the app can refresh content when running in the background.
enum UIBackgroundRefreshStatus
Constants that indicate whether background execution is enabled for the app.
class let backgroundRefreshStatusDidChangeNotification: NSNotification.Name
A notification that posts when the app’s status for downloading content in the background changes.
Marks the start of a task with a custom name that should continue if the app enters the background.
func endBackgroundTask(UIBackgroundTaskIdentifier)
Marks the end of a specific long-running background task.
struct UIBackgroundTaskIdentifier
A unique token that identifies a request to run in the background.
var backgroundTimeRemaining: TimeInterval
The maximum amount of time remaining for the app to run in the background.
https://developer.apple.com/documentation/uikit/uiapplication/beginbackgroundtask(withname:expirationhandler:)
#app-main)
- UIKit
- UIApplication
- beginBackgroundTask(withName:expirationHandler:)
Instance Method
beginBackgroundTask(withName:expirationHandler:)
Marks the start of a task with a custom name that should continue if the app enters the background.
tvOS
iOS, iPadOS, Mac Catalyst
nonisolated func beginBackgroundTask( withName taskName: String?,
tvOS, visionOS
Parameters
taskName
The name to display in the debugger when viewing the background task. If you specify nil for this parameter, the method generates a name based on the name of the calling function or method.
handler
A handler to be called shortly before the app’s remaining background time reaches 0. Use this handler to clean up and mark the end of the background task. Failure to end the task explicitly will result in the termination of the app. The system calls the handler synchronously on the main thread, blocking the app’s suspension momentarily.
Return Value
A unique identifier for the new background task. You must pass this value to the endBackgroundTask(_:) method to mark the end of this task. This method returns invalid if running in the background isn’t possible.
Mentioned in
Extending your app’s background execution time
Discussion
This method requests additional background execution time for your app. Call this method when leaving a task unfinished might be detrimental to your app’s user experience. For example, call this method before writing data to a file to prevent the system from suspending your app while the operation is in progress. For background tasks requiring more time, use Background Tasks.
Call this method as early as possible before starting your task, preferably before your app actually enters the background. The method requests the task assertion for your app asynchronously. If you call this method shortly before your app is due to be suspended, there’s a chance that the system might suspend your app before that task assertion is granted. For example, don’t call this method at the very end of your applicationDidEnterBackground(_:) method and expect your app to continue running. If the system is unable to grant the task assertion, it calls your expiration handler.
Each call to this method must be balanced by a matching call to the endBackgroundTask(_:) method. Apps running background tasks have a finite amount of time in which to run them. (You can find out the maximum background time available using the backgroundTimeRemaining property.) If you don’t call endBackgroundTask(_:) for each task before time expires, the system kills the app. If you provide a block object in the handler parameter, the system calls your handler before time expires to give you a chance to end the task.
You can call this method at any point in your app’s execution. You may also call this method multiple times to mark the beginning of several background tasks that run in parallel. However, each task must be ended separately. You identify a given task using the value returned by this method.
This method can be safely called on a non-main thread. To extend the execution time of an app extension, use the performExpiringActivity(withReason:using:) method of ProcessInfo instead.
See Also
Related Documentation
Background Tasks
Support background processing in your app by wrapping your app’s most critical work in framework-provided tasks.
Managing background tasks
var backgroundRefreshStatus: UIBackgroundRefreshStatus
Indicates whether the app can refresh content when running in the background.
enum UIBackgroundRefreshStatus
Constants that indicate whether background execution is enabled for the app.
class let backgroundRefreshStatusDidChangeNotification: NSNotification.Name
A notification that posts when the app’s status for downloading content in the background changes.
Marks the start of a task that should continue if the app enters the background.
func endBackgroundTask(UIBackgroundTaskIdentifier)
Marks the end of a specific long-running background task.
struct UIBackgroundTaskIdentifier
A unique token that identifies a request to run in the background.
var backgroundTimeRemaining: TimeInterval
The maximum amount of time remaining for the app to run in the background.
https://developer.apple.com/documentation/uikit/uiapplication/schedulelocalnotification(_:)
#app-main)
- UIKit
- UIApplication
- scheduleLocalNotification(_:) Deprecated
Instance Method
scheduleLocalNotification(_:)
Schedules a local notification for delivery at its encapsulated date and time.
iOS 4.0–10.0DeprecatediPadOS 4.0–10.0DeprecatedMac Catalyst 13.1–13.1Deprecated
@MainActor func scheduleLocalNotification(_ notification: UILocalNotification)
Parameters
notification
The local notification object that you want to schedule. This object contains information about when to deliver the notification and what to do when that date occurs. The system keeps a copy of this object so you may release the object once it is scheduled.
Discussion
Prior to scheduling any local notifications, you must call the registerUserNotificationSettings(_:) method to let the system know what types of alerts, if any, you plan to display to the user.
See Also
Deprecated methods
Asks the system to activate an existing scene, or create a new scene and associate it with your app.
Deprecated
func beginIgnoringInteractionEvents()
Tells the receiver to suspend the handling of touch-related events.
func endIgnoringInteractionEvents()
Tells the receiver to resume the handling of touch-related events.
func setMinimumBackgroundFetchInterval(TimeInterval)
Specifies the minimum amount of time that must elapse between background fetch operations.
func presentLocalNotificationNow(UILocalNotification)
Presents a local notification immediately.
func cancelLocalNotification(UILocalNotification)
Cancels the delivery of the specified scheduled local notification.
func cancelAllLocalNotifications()
Cancels the delivery of all scheduled local notifications.
Configures a periodic handler for VoIP apps in older versions of iOS.
let UIMinimumKeepAliveTimeout: TimeInterval
The minimum amount of time (measured in seconds) an app may run a critical background task in the background.
func clearKeepAliveTimeout()
Removes a previously installed periodic handler block.
func setStatusBarHidden(Bool, with: UIStatusBarAnimation)
Hides or shows the status bar, optionally animating the transition.
func setStatusBarStyle(UIStatusBarStyle, animated: Bool)
Sets the style of the status bar, optionally animating the transition to the new style.
func setStatusBarOrientation(UIInterfaceOrientation, animated: Bool)
Sets the app’s status bar to the specified orientation, optionally animating the transition.
func registerUserNotificationSettings(UIUserNotificationSettings)
Registers your preferred options for notifying the user.
func registerForRemoteNotifications(matching: UIRemoteNotificationType)
Register to receive remote notifications of the specified types via Apple Push Notification service.
https://developer.apple.com/documentation/uikit/uiapplication/cancellocalnotification(_:)
#app-main)
- UIKit
- UIApplication
- cancelLocalNotification(_:) Deprecated
Instance Method
cancelLocalNotification(_:)
Cancels the delivery of the specified scheduled local notification.
iOS 4.0–10.0DeprecatediPadOS 4.0–10.0DeprecatedMac Catalyst 13.1–13.1Deprecated
@MainActor func cancelLocalNotification(_ notification: UILocalNotification)
Parameters
notification
The local notification to cancel.
Discussion
Calling this method also programmatically dismisses the notification if it is currently displaying an alert.
See Also
Deprecated methods
Asks the system to activate an existing scene, or create a new scene and associate it with your app.
Deprecated
func beginIgnoringInteractionEvents()
Tells the receiver to suspend the handling of touch-related events.
func endIgnoringInteractionEvents()
Tells the receiver to resume the handling of touch-related events.
func setMinimumBackgroundFetchInterval(TimeInterval)
Specifies the minimum amount of time that must elapse between background fetch operations.
func scheduleLocalNotification(UILocalNotification)
Schedules a local notification for delivery at its encapsulated date and time.
func presentLocalNotificationNow(UILocalNotification)
Presents a local notification immediately.
func cancelAllLocalNotifications()
Cancels the delivery of all scheduled local notifications.
Configures a periodic handler for VoIP apps in older versions of iOS.
let UIMinimumKeepAliveTimeout: TimeInterval
The minimum amount of time (measured in seconds) an app may run a critical background task in the background.
func clearKeepAliveTimeout()
Removes a previously installed periodic handler block.
func setStatusBarHidden(Bool, with: UIStatusBarAnimation)
Hides or shows the status bar, optionally animating the transition.
func setStatusBarStyle(UIStatusBarStyle, animated: Bool)
Sets the style of the status bar, optionally animating the transition to the new style.
func setStatusBarOrientation(UIInterfaceOrientation, animated: Bool)
Sets the app’s status bar to the specified orientation, optionally animating the transition.
func registerUserNotificationSettings(UIUserNotificationSettings)
Registers your preferred options for notifying the user.
func registerForRemoteNotifications(matching: UIRemoteNotificationType)
Register to receive remote notifications of the specified types via Apple Push Notification service.
https://developer.apple.com/documentation/uikit/uiapplication/beginreceivingremotecontrolevents()
#app-main)
- UIKit
- UIApplication
- beginReceivingRemoteControlEvents()
Instance Method
beginReceivingRemoteControlEvents()
Tells the app to begin receiving remote-control events.
tvOS
@MainActor func beginReceivingRemoteControlEvents()
Discussion
In iOS 7.1 and later, use the shared MPRemoteCommandCenter object to register for remote control events. You do not need to call this method when using the shared command center object.
This method starts the delivery of remote control events using the responder chain. Remote-control events originate as commands issued by headsets and external accessories that are intended to control multimedia presented by an app. To stop the reception of remote-control events, you must call endReceivingRemoteControlEvents().
See Also
Receiving remote control events
func endReceivingRemoteControlEvents()
Tells the app to stop receiving remote-control events.
https://developer.apple.com/documentation/uikit/uiapplication/endreceivingremotecontrolevents()
#app-main)
- UIKit
- UIApplication
- endReceivingRemoteControlEvents()
Instance Method
endReceivingRemoteControlEvents()
Tells the app to stop receiving remote-control events.
tvOS
@MainActor func endReceivingRemoteControlEvents()
Discussion
In iOS 7.1 and later, use the shared MPRemoteCommandCenter object to unregister for remote control events. You do not need to call this method when using the shared command center object.
This method stops the delivery of remote control events using the responder chain. Remote-control events originate as commands issued by headsets and external accessories that are intended to control multimedia presented by an app.
See Also
Receiving remote control events
func beginReceivingRemoteControlEvents()
Tells the app to begin receiving remote-control events.
https://developer.apple.com/documentation/uikit/uiapplication/sendevent(_:)
#app-main)
- UIKit
- UIApplication
- sendEvent(_:)
Instance Method
sendEvent(_:)
Dispatches an event to the appropriate responder objects in the app.
tvOS
@MainActor func sendEvent(_ event: UIEvent)
Parameters
event
A UIEvent object encapsulating the information about an event, including the touches involved.
Discussion
If you require it, you can intercept incoming events by subclassing UIApplication and overriding this method. For every event you intercept, you must dispatch it by calling [super sendEvent:event] after handling the event in your implementation.
See Also
Controlling and handling events
Sends an action message identified by the selector to a specified target.
var applicationSupportsShakeToEdit: Bool
A Boolean value that determines whether shaking the device displays the undo-redo user interface.
https://developer.apple.com/documentation/uikit/uiapplication/sendaction(_:to:from:for:)
#app-main)
- UIKit
- UIApplication
- sendAction(_:to:from:for:)
Instance Method
sendAction(_:to:from:for:)
Sends an action message identified by the selector to a specified target.
tvOS
@MainActor func sendAction( _ action: Selector, to target: Any?, from sender: Any?, for event: UIEvent?
Parameters
action
A selector identifying an action method. See the discussion for information on the permitted selector forms.
target
The object to receive the action message. If target is nil, the app sends the message to the first responder, from whence it progresses up the responder chain until it is handled.
sender
The object that is sending the action message. The default sender is the UIControl object that invokes this method.
event
A UIEvent object that encapsulates information about the event originating the action message.
Return Value
true if a responder object handled the action message, false if no object in the responder chain handled the message.
Discussion
Normally, this method is invoked by a UIControl object that the user has touched. The default implementation dispatches the action method to the given target object or, if no target is specified, to the first responder. Subclasses may override this method to perform special dispatching of action messages.
By default, this method pushes two parameters when calling the target. These last two parameters are optional for the receiver because it is up to the caller (usually a UIControl object) to remove any parameters it added. This design enables the action selector to be one of the following:
-
- (void)action -
- (void)action:(id)sender -
- (void)action:(id)sender forEvent:(UIEvent *)event
See Also
Controlling and handling events
func sendEvent(UIEvent)
Dispatches an event to the appropriate responder objects in the app.
var applicationSupportsShakeToEdit: Bool
A Boolean value that determines whether shaking the device displays the undo-redo user interface.
https://developer.apple.com/documentation/uikit/uiapplication/delegate
- UIKit
- UIApplication
- delegate
Instance Property
delegate
The delegate of the app object.
tvOS
@MainActor unowned(unsafe) var delegate: (any UIApplicationDelegate)? { get set }
Discussion
Every app must have an app delegate object to respond to app-related messages. For example, the app notifies its delegate when the app finishes launching and when its foreground or background execution status changes. Similarly, app-related messages coming from the system are often routed to the app delegate for handling. Xcode provides an initial app delegate for every app and you should not need to change this delegate later.
The delegate must adopt the UIApplicationDelegate formal protocol.
See Also
Configuring your app’s behavior
protocol UIApplicationDelegate
A set of methods to manage shared behaviors for your app.
https://developer.apple.com/documentation/uikit/uiapplication/unregisterforremotenotifications()
#app-main)
- UIKit
- UIApplication
- unregisterForRemoteNotifications()
Instance Method
unregisterForRemoteNotifications()
Unregisters for all remote notifications received through Apple Push Notification service.
tvOS
@MainActor func unregisterForRemoteNotifications()
Discussion
You should call this method in rare circumstances only, such as when a new version of the app removes support for all types of remote notifications. Users can temporarily prevent apps from receiving remote notifications through the Notifications section of the Settings app. Apps unregistered through this method can always re-register.
See Also
Registering for remote notifications
func registerForRemoteNotifications()
Registers to receive remote notifications through Apple Push Notification service.
var isRegisteredForRemoteNotifications: Bool
A Boolean value that indicates whether the app is currently registered for remote notifications.
https://developer.apple.com/documentation/uikit/uiapplication/isregisteredforremotenotifications
- UIKit
- UIApplication
- isRegisteredForRemoteNotifications
Instance Property
isRegisteredForRemoteNotifications
A Boolean value that indicates whether the app is currently registered for remote notifications.
tvOS
@MainActor var isRegisteredForRemoteNotifications: Bool { get }
Discussion
This method reflects whether the remote registration process completed successfully—a process that begins when you call the registerForRemoteNotifications() method. This method does not reflect whether remote notifications are actually available due to connectivity issues. The value returned by this method takes into account the user’s preferences for receiving remote notifications.
See Also
Registering for remote notifications
func registerForRemoteNotifications()
Registers to receive remote notifications through Apple Push Notification service.
func unregisterForRemoteNotifications()
Unregisters for all remote notifications received through Apple Push Notification service.
https://developer.apple.com/documentation/uikit/uiapplication/applicationstate
- UIKit
- UIApplication
- applicationState
Instance Property
applicationState
The app’s current state, or that of its most active scene.
tvOS
@MainActor var applicationState: UIApplication.State { get }
Discussion
The behavior of this property depends on whether your app is scene-based.
In a scene-based app, this property takes the value of the most active scene, which it determines from each scene’s activationState property. A scene-based app launches in the background state, and transitions between its states as scenes connect, change their states, and disconnect. For scene-based apps, use UISceneDelegate to respond to changes in an individual scene’s life cycle.
In a sceneless app, the property’s value is always the app’s current state. The app is inactive at launch, and then is generally in either an active or background state. The app may become inactive for a short period — for example, when transitioning between active and background states, when the system presents an alert in front of it, or when the system displays the application switcher. For sceneless apps, use UIApplicationDelegate to respond to the app’s life cycle changes.
See Also
Getting the application state
enum State
Constants that indicate the running states of an app.
https://developer.apple.com/documentation/uikit/uiapplication/state
- UIKit
- UIApplication
- UIApplication.State
Enumeration
UIApplication.State
Constants that indicate the running states of an app.
tvOS
enum State
Topics
Constants
case active
The app is running in the foreground and currently receiving events.
case inactive
The app is running in the foreground but isn’t receiving events.
case background
The app is running in the background.
Initializers
init?(rawValue: Int)
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Getting the application state
var applicationState: UIApplication.State
The app’s current state, or that of its most active scene.
https://developer.apple.com/documentation/uikit/uiapplication/supportsmultiplescenes
- UIKit
- UIApplication
- supportsMultipleScenes
Instance Property
supportsMultipleScenes
A Boolean value that indicates whether the app may display multiple scenes simultaneously.
@MainActor var supportsMultipleScenes: Bool { get }
Discussion
UIKit sets this property to true when the system allows the app to display multiple scenes and the app’s Info.plist file includes the UIApplicationSupportsMultipleScenes key with a value of true. If either of those conditions isn’t true, the value of this property is false.
Use the connectedScenes property to determine whether multiple scenes are present.
See Also
Getting scene information
The app’s currently connected scenes.
The sessions whose scenes are either currently active or archived by the system.
https://developer.apple.com/documentation/uikit/uiapplication/connectedscenes
https://developer.apple.com/documentation/uikit/uiapplication/opensessions
https://developer.apple.com/documentation/uikit/uiapplication/activatescenesession(for:errorhandler:)
#app-main)
- UIKit
- UIApplication
- activateSceneSession(for:errorHandler:)
Instance Method
activateSceneSession(for:errorHandler:)
Asks the system to activate an existing scene or create a new scene and associate it with your app.
Mac CatalystvisionOS
@MainActor @preconcurrency func activateSceneSession( for request: UISceneSessionActivationRequest,
)
Parameters
request
The activation request.
errorHandler
A handler to call if the request fails.
See Also
Related Documentation
Asks the system to activate an existing scene, or create a new scene and associate it with your app.
Deprecated
Managing a scene’s life cycle
Asks the system to dismiss an existing scene and remove it from the app switcher.
func requestSceneSessionRefresh(UISceneSession)
Asks the system to update any system UI associated with the specified scene.
struct UISceneSessionActivationRequest
A collection of properties that you use to request activation of a scene.
class ActivationRequestOptions
An object that contains information you want the system to use when activating the session associated with a scene.
class UISceneDestructionRequestOptions
An object you pass to UIKit to permanently remove a scene and its associated session from your app.
https://developer.apple.com/documentation/uikit/uiapplication/requestscenesessiondestruction(_:options:errorhandler:)
#app-main)
- UIKit
- UIApplication
- requestSceneSessionDestruction(_:options:errorHandler:)
Instance Method
requestSceneSessionDestruction(_:options:errorHandler:)
Asks the system to dismiss an existing scene and remove it from the app switcher.
@MainActor func requestSceneSessionDestruction( _ sceneSession: UISceneSession, options: UISceneDestructionRequestOptions?,
)
Parameters
sceneSession
The session whose scene you want to remove from the screen and app switcher.
options
Information for the system to use when dismissing the scene. For information about how to create this object, see UISceneDestructionRequestOptions.
errorHandler
An error handler block to execute if a problem occurs. The method does not execute this block when it successfully dismisses the scene. This block has no return value and has the following parameter:
error
The NSError object describing the problem that occurred.
Discussion
If the specified scene is onscreen, calling this method dismisses it using the specified options. The method sends a disconnect notification to the scene and then calls your app delegate’s application(_:didDiscardSceneSessions:) method.
See Also
Managing a scene’s life cycle
Asks the system to activate an existing scene or create a new scene and associate it with your app.
func requestSceneSessionRefresh(UISceneSession)
Asks the system to update any system UI associated with the specified scene.
struct UISceneSessionActivationRequest
A collection of properties that you use to request activation of a scene.
class ActivationRequestOptions
An object that contains information you want the system to use when activating the session associated with a scene.
class UISceneDestructionRequestOptions
An object you pass to UIKit to permanently remove a scene and its associated session from your app.
https://developer.apple.com/documentation/uikit/uiapplication/requestscenesessionrefresh(_:)
#app-main)
- UIKit
- UIApplication
- requestSceneSessionRefresh(_:)
Instance Method
requestSceneSessionRefresh(_:)
Asks the system to update any system UI associated with the specified scene.
@MainActor func requestSceneSessionRefresh(_ sceneSession: UISceneSession)
Parameters
sceneSession
The session whose scene you want to update.
Discussion
Call this method when your scene is in the background and any part of your scene’s visible appearance changes. For example, call this method after updating your scene’s content to let the system know your scene’s snapshot requires refreshing. You don’t need to call this method when your scene is running in the foreground.
See Also
Managing a scene’s life cycle
Asks the system to activate an existing scene or create a new scene and associate it with your app.
Asks the system to dismiss an existing scene and remove it from the app switcher.
struct UISceneSessionActivationRequest
A collection of properties that you use to request activation of a scene.
class ActivationRequestOptions
An object that contains information you want the system to use when activating the session associated with a scene.
class UISceneDestructionRequestOptions
An object you pass to UIKit to permanently remove a scene and its associated session from your app.
https://developer.apple.com/documentation/uikit/uiscenesessionactivationrequest-swift.struct
- UIKit
- UISceneSessionActivationRequest
Structure
UISceneSessionActivationRequest
A collection of properties that you use to request activation of a scene.
Mac CatalystvisionOS
struct UISceneSessionActivationRequest
Overview
A UISceneSessionActiviationRequest object provides information about how to activate a scene session. Create a request to specify:
-
A user activity for the scene session.
-
An existing scene session.
-
A scene session with a specific role.
You create a UISceneSessionActivationRequest object in your code, then you pass it as a parameter when you call activateSceneSession(for:errorHandler:) to ask the system to activate the scene session.
Topics
Creating a request
init(role: UISceneSession.Role, userActivity: NSUserActivity?, options: UIScene.ActivationRequestOptions?)
Creates a scene session activation request object with a role, a user activity, and options that you provide.
init(session: UISceneSession, userActivity: NSUserActivity?, options: UIScene.ActivationRequestOptions?)
Creates a scene session activation request object with a scene session, a user activity, and options that you provide.
Managing request details
var options: UIScene.ActivationRequestOptions?
Activation request options to further customize the request.
var role: UISceneSession.Role
The role to request.
var session: UISceneSession?
The specific scene session to activate.
var userActivity: NSUserActivity?
A user activity to send to the newly activated scene.
Initializers
Creates a UISceneSessionActivationRequest customized to open a SwiftUI scene.
Creates a UISceneSessionActivationRequest customized to open a SwiftUI scene with the given identifier.
Creates a UISceneSessionActivationRequest customized to open a SwiftUI scene with the given identifier and presented value.
Creates a UISceneSessionActivationRequest customized to open a SwiftUI scene with a presented value.
Relationships
Conforms To
EquatableHashable
See Also
Managing a scene’s life cycle
Asks the system to activate an existing scene or create a new scene and associate it with your app.
Asks the system to dismiss an existing scene and remove it from the app switcher.
func requestSceneSessionRefresh(UISceneSession)
Asks the system to update any system UI associated with the specified scene.
class ActivationRequestOptions
An object that contains information you want the system to use when activating the session associated with a scene.
class UISceneDestructionRequestOptions
An object you pass to UIKit to permanently remove a scene and its associated session from your app.
https://developer.apple.com/documentation/uikit/uiscene/activationrequestoptions
- UIKit
- UIScene
- UIScene.ActivationRequestOptions
Class
UIScene.ActivationRequestOptions
An object that contains information you want the system to use when activating the session associated with a scene.
@MainActor class ActivationRequestOptions
Overview
Create a UIScene.ActivationRequestOptions object before you activate or create a scene using the activateSceneSession(for:errorHandler:) (Swift) or activateSceneSessionForRequest:errorHandler: (Objective-C) method of UIApplication. Use this object to specify which of your app’s existing scenes originated the request for the new scene.
Topics
Specifying the originator of the request
var requestingScene: UIScene?
The scene object that requested the activation of a different scene.
Specifying collection join behavior
var collectionJoinBehavior: UISceneCollectionJoinBehavior
The behavior that specifies how a new scene joins a scene collection.
enum UISceneCollectionJoinBehavior
A set of behaviors that specify how a new scene joins a scene collection.
Relationships
Inherits From
NSObject
Inherited By
UIWindowScene.ActivationRequestOptions
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendable
See Also
Managing a scene’s life cycle
Asks the system to activate an existing scene or create a new scene and associate it with your app.
Asks the system to dismiss an existing scene and remove it from the app switcher.
func requestSceneSessionRefresh(UISceneSession)
Asks the system to update any system UI associated with the specified scene.
struct UISceneSessionActivationRequest
A collection of properties that you use to request activation of a scene.
class UISceneDestructionRequestOptions
An object you pass to UIKit to permanently remove a scene and its associated session from your app.
https://developer.apple.com/documentation/uikit/uiscenedestructionrequestoptions
https://developer.apple.com/documentation/uikit/uiapplication/backgroundrefreshstatus
- UIKit
- UIApplication
- backgroundRefreshStatus
Instance Property
backgroundRefreshStatus
Indicates whether the app can refresh content when running in the background.
@MainActor var backgroundRefreshStatus: UIBackgroundRefreshStatus { get }
Discussion
You can use this property to determine whether Background App Refresh—an app’s ability to open in the background to perform refresh tasks—is enabled, and warn the user if it is not. Don’t warn the user if the value of this property is set to UIBackgroundRefreshStatus.restricted. A restricted user, such as one who is managed under parental controls, can’t enable Background App Refresh.
Background App Refresh is disabled automatically when a device is operating in low-power mode. When this happens, the time available for performing background tasks is reduced to save power.
See Also
Managing background tasks
enum UIBackgroundRefreshStatus
Constants that indicate whether background execution is enabled for the app.
class let backgroundRefreshStatusDidChangeNotification: NSNotification.Name
A notification that posts when the app’s status for downloading content in the background changes.
Marks the start of a task with a custom name that should continue if the app enters the background.
Marks the start of a task that should continue if the app enters the background.
func endBackgroundTask(UIBackgroundTaskIdentifier)
Marks the end of a specific long-running background task.
struct UIBackgroundTaskIdentifier
A unique token that identifies a request to run in the background.
var backgroundTimeRemaining: TimeInterval
The maximum amount of time remaining for the app to run in the background.
https://developer.apple.com/documentation/uikit/uibackgroundrefreshstatus
- UIKit
- UIBackgroundRefreshStatus
Enumeration
UIBackgroundRefreshStatus
Constants that indicate whether background execution is enabled for the app.
enum UIBackgroundRefreshStatus
Topics
Constants
case restricted
Background updates are unavailable and the user cannot enable them again.
case denied
The user explicitly disabled background behavior for this app or for the whole system.
case available
Background updates are available for the app.
Initializers
init?(rawValue: Int)
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Managing background tasks
var backgroundRefreshStatus: UIBackgroundRefreshStatus
Indicates whether the app can refresh content when running in the background.
class let backgroundRefreshStatusDidChangeNotification: NSNotification.Name
A notification that posts when the app’s status for downloading content in the background changes.
Marks the start of a task with a custom name that should continue if the app enters the background.
Marks the start of a task that should continue if the app enters the background.
func endBackgroundTask(UIBackgroundTaskIdentifier)
Marks the end of a specific long-running background task.
struct UIBackgroundTaskIdentifier
A unique token that identifies a request to run in the background.
var backgroundTimeRemaining: TimeInterval
The maximum amount of time remaining for the app to run in the background.
https://developer.apple.com/documentation/uikit/uiapplication/backgroundrefreshstatusdidchangenotification
- UIKit
- UIApplication
- backgroundRefreshStatusDidChangeNotification
Type Property
backgroundRefreshStatusDidChangeNotification
A notification that posts when the app’s status for downloading content in the background changes.
nonisolated class let backgroundRefreshStatusDidChangeNotification: NSNotification.Name
Discussion
The system sends this notification when the backgroundRefreshStatus property of the app object changes. That property can change in response to the user disabling multitasking support for the app. The object of the notification is the UIApplication object. There is no userInfo dictionary.
See Also
Managing background tasks
var backgroundRefreshStatus: UIBackgroundRefreshStatus
Indicates whether the app can refresh content when running in the background.
enum UIBackgroundRefreshStatus
Constants that indicate whether background execution is enabled for the app.
Marks the start of a task with a custom name that should continue if the app enters the background.
Marks the start of a task that should continue if the app enters the background.
func endBackgroundTask(UIBackgroundTaskIdentifier)
Marks the end of a specific long-running background task.
struct UIBackgroundTaskIdentifier
A unique token that identifies a request to run in the background.
var backgroundTimeRemaining: TimeInterval
The maximum amount of time remaining for the app to run in the background.
https://developer.apple.com/documentation/uikit/uiapplication/endbackgroundtask(_:)
#app-main)
- UIKit
- UIApplication
- endBackgroundTask(_:)
Instance Method
endBackgroundTask(_:)
Marks the end of a specific long-running background task.
tvOS
nonisolated func endBackgroundTask(_ identifier: UIBackgroundTaskIdentifier)
Parameters
identifier
An identifier returned by the beginBackgroundTask(expirationHandler:) method.
Mentioned in
Extending your app’s background execution time
Discussion
You must call this method to end a task that was started using the beginBackgroundTask(expirationHandler:) method. If you do not, the system may terminate your app.
This method can be safely called on a non-main thread.
See Also
Managing background tasks
var backgroundRefreshStatus: UIBackgroundRefreshStatus
Indicates whether the app can refresh content when running in the background.
enum UIBackgroundRefreshStatus
Constants that indicate whether background execution is enabled for the app.
class let backgroundRefreshStatusDidChangeNotification: NSNotification.Name
A notification that posts when the app’s status for downloading content in the background changes.
Marks the start of a task with a custom name that should continue if the app enters the background.
Marks the start of a task that should continue if the app enters the background.
struct UIBackgroundTaskIdentifier
A unique token that identifies a request to run in the background.
var backgroundTimeRemaining: TimeInterval
The maximum amount of time remaining for the app to run in the background.
https://developer.apple.com/documentation/uikit/uibackgroundtaskidentifier
- UIKit
- UIBackgroundTaskIdentifier
Structure
UIBackgroundTaskIdentifier
A unique token that identifies a request to run in the background.
iOSiPadOSMac CatalysttvOSvisionOS
struct UIBackgroundTaskIdentifier
Topics
Identifier
static let invalid: UIBackgroundTaskIdentifier
A token that indicates an invalid task request.
Initializers
init(rawValue: Int)
Creates a new instance with the specified raw value.
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Managing background tasks
var backgroundRefreshStatus: UIBackgroundRefreshStatus
Indicates whether the app can refresh content when running in the background.
enum UIBackgroundRefreshStatus
Constants that indicate whether background execution is enabled for the app.
class let backgroundRefreshStatusDidChangeNotification: NSNotification.Name
A notification that posts when the app’s status for downloading content in the background changes.
Marks the start of a task with a custom name that should continue if the app enters the background.
Marks the start of a task that should continue if the app enters the background.
func endBackgroundTask(UIBackgroundTaskIdentifier)
Marks the end of a specific long-running background task.
var backgroundTimeRemaining: TimeInterval
The maximum amount of time remaining for the app to run in the background.
https://developer.apple.com/documentation/uikit/uiapplication/backgroundtimeremaining
- UIKit
- UIApplication
- backgroundTimeRemaining
Instance Property
backgroundTimeRemaining
The maximum amount of time remaining for the app to run in the background.
tvOS
nonisolated var backgroundTimeRemaining: TimeInterval { get }
Mentioned in
Extending your app’s background execution time
Discussion
The value is valid only after the app enters the background and has started at least one task using beginBackgroundTask(expirationHandler:) in the foreground.
System conditions may end background execution earlier, either by calling the expiration handler, or by terminating the app.
This method can be safely called on a non-main thread.
See Also
Managing background tasks
var backgroundRefreshStatus: UIBackgroundRefreshStatus
Indicates whether the app can refresh content when running in the background.
enum UIBackgroundRefreshStatus
Constants that indicate whether background execution is enabled for the app.
class let backgroundRefreshStatusDidChangeNotification: NSNotification.Name
A notification that posts when the app’s status for downloading content in the background changes.
Marks the start of a task with a custom name that should continue if the app enters the background.
Marks the start of a task that should continue if the app enters the background.
func endBackgroundTask(UIBackgroundTaskIdentifier)
Marks the end of a specific long-running background task.
struct UIBackgroundTaskIdentifier
A unique token that identifies a request to run in the background.
https://developer.apple.com/documentation/uikit/uiapplication/backgroundfetchintervalminimum
https://developer.apple.com/documentation/uikit/uiapplication/backgroundfetchintervalnever
- UIKit
- UIApplication
- backgroundFetchIntervalNever
Type Property
backgroundFetchIntervalNever
A fetch interval large enough to prevent fetch operations from occurring.
class let backgroundFetchIntervalNever: TimeInterval
See Also
Fetching content in the background
class let backgroundFetchIntervalMinimum: TimeInterval
The smallest fetch interval supported by the system.
https://developer.apple.com/documentation/uikit/uiapplication/openexternalurloptionskey
- UIKit
- UIApplication
- UIApplication.OpenExternalURLOptionsKey
Structure
UIApplication.OpenExternalURLOptionsKey
Options for opening a URL.
iOSiPadOSMac CatalysttvOSvisionOS
struct OpenExternalURLOptionsKey
Topics
URL options
static let universalLinksOnly: UIApplication.OpenExternalURLOptionsKey
URLs must be universal links and have an app configured to open them.
Measuring ad taps
static let eventAttribution: UIApplication.OpenExternalURLOptionsKey
An object you use to send tap event attribution data to the browser for Private Click Measurement.
Initializers
init(rawValue: String)
Creates a new instance with the specified raw value.
Relationships
Conforms To
EquatableHashableRawRepresentableSendableSendableMetatype
See Also
Opening a URL resource
Attempts to asynchronously open the resource at the specified URL.
Returns a Boolean value that indicates whether an app is available to handle a URL scheme.
https://developer.apple.com/documentation/uikit/uiapplication/opensettingsurlstring
- UIKit
- UIApplication
- openSettingsURLString
Type Property
openSettingsURLString
The URL string you use to deep link to your app’s custom settings in the Settings app.
tvOS
nonisolated class let openSettingsURLString: String
Discussion
Create a URL from this value and pass it to the open(_:options:completionHandler:) method to launch the Settings app and display your app’s custom settings, if it has any.
// Create the URL that deep links to your app's custom settings. if let url = URL(string: UIApplication.openSettingsURLString) { // Ask the system to open that URL. await UIApplication.shared.open(url) }
// Create the URL that deep links to your app's custom settings.
NSURL *url = [[NSURL alloc] initWithString:UIApplicationOpenSettingsURLString];
// Ask the system to open that URL.
[[UIApplication sharedApplication] openURL:url
options:@{}
completionHandler:nil];
For design guidance, see Human Interface Guidelines.
See Also
Deep linking to custom settings
static let openNotificationSettingsURLString: String
The URL string you use to deep link to your app’s notification settings in the Settings app.
let UIApplicationOpenNotificationSettingsURLString: String
A constant that provides the URL string you use to deep link to your app’s notification settings in the Settings app.
Deprecated
class let openDefaultApplicationsSettingsURLString: String
The URL string used to select a default app in the Settings app.
https://developer.apple.com/documentation/uikit/uiapplication/opennotificationsettingsurlstring
- UIKit
- UIApplication
- openNotificationSettingsURLString
Type Property
openNotificationSettingsURLString
The URL string you use to deep link to your app’s notification settings in the Settings app.
Mac CatalysttvOSvisionOS
nonisolated static let openNotificationSettingsURLString: String
Discussion
Create a URL from this value and pass it to the open(_:options:completionHandler:) method to launch the Settings app and display your app’s notification settings, if it has any.
// Create the URL that deep links to your app's notification settings. if let url = URL(string: UIApplication.openNotificationSettingsURLString) { // Ask the system to open that URL. await UIApplication.shared.open(url) }
See Also
Deep linking to custom settings
class let openSettingsURLString: String
The URL string you use to deep link to your app’s custom settings in the Settings app.
let UIApplicationOpenNotificationSettingsURLString: String
A constant that provides the URL string you use to deep link to your app’s notification settings in the Settings app.
Deprecated
class let openDefaultApplicationsSettingsURLString: String
The URL string used to select a default app in the Settings app.
https://developer.apple.com/documentation/uikit/uiapplicationopennotificationsettingsurlstring
- UIKit
- UIApplicationOpenNotificationSettingsURLString Deprecated
Global Variable
UIApplicationOpenNotificationSettingsURLString
A constant that provides the URL string you use to deep link to your app’s notification settings in the Settings app.
iOS 15.4–16.0DeprecatediPadOS 15.4–16.0DeprecatedMac Catalyst 15.4–16.0DeprecatedtvOS 15.4–16.0DeprecatedvisionOS 1.0–1.0DeprecatedwatchOS 8.5–9.0Deprecated
nonisolated let UIApplicationOpenNotificationSettingsURLString: String
Discussion
Create a URL from this value and pass it to the open(_:options:completionHandler:) method to launch the Settings app and display your app’s notification settings, if it has any.
// Create the URL that deep links to your app's notification settings.
NSURL *url = [[NSURL alloc] initWithString:UIApplicationOpenNotificationSettingsURLString];
// Ask the system to open that URL.
[[UIApplication sharedApplication] openURL:url
options:@{}
completionHandler:nil];
See Also
Deep linking to custom settings
class let openSettingsURLString: String
The URL string you use to deep link to your app’s custom settings in the Settings app.
static let openNotificationSettingsURLString: String
The URL string you use to deep link to your app’s notification settings in the Settings app.
class let openDefaultApplicationsSettingsURLString: String
The URL string used to select a default app in the Settings app.
https://developer.apple.com/documentation/uikit/uiapplication/opendefaultapplicationssettingsurlstring
- UIKit
- UIApplication
- openDefaultApplicationsSettingsURLString
Type Property
openDefaultApplicationsSettingsURLString
The URL string used to select a default app in the Settings app.
nonisolated class let openDefaultApplicationsSettingsURLString: String
Discussion
Create a URL from this value and pass it to the open(_:options:completionHandler:) method to launch the Settings app and display your app’s custom settings, if it has any:
// Create the URL that links to the Settings app for default app selection. if let url = URL(string: UIApplication.openDefaultApplicationsSettingsURLString) { // Ask the system to open that URL. await UIApplication.shared.open(url) }
// Create the URL that links to the Settings app for default app selection.
NSURL *url = [[NSURL alloc] initWithString:UIApplicationOpenDefaultApplicationsSettingsURLString];
// Ask the system to open that URL.
[[UIApplication sharedApplication] openURL:url
options:@{}
completionHandler:nil];
See Also
Deep linking to custom settings
class let openSettingsURLString: String
The URL string you use to deep link to your app’s custom settings in the Settings app.
static let openNotificationSettingsURLString: String
The URL string you use to deep link to your app’s notification settings in the Settings app.
let UIApplicationOpenNotificationSettingsURLString: String
A constant that provides the URL string you use to deep link to your app’s notification settings in the Settings app.
Deprecated
https://developer.apple.com/documentation/uikit/uiapplication/isidletimerdisabled
- UIKit
- UIApplication
- isIdleTimerDisabled
Instance Property
isIdleTimerDisabled
A Boolean value that controls whether the idle timer is disabled for the app.
tvOS
@MainActor var isIdleTimerDisabled: Bool { get set }
Discussion
The default value of this property is false. When most apps have no touches as user input for a short period, the system puts the device into a “sleep” state where the screen dims. This is done for the purposes of conserving power. However, apps that don’t have user input except for the accelerometer — games, for instance — can, by setting this property to true, disable the “idle timer” to avert system sleep.
https://developer.apple.com/documentation/uikit/uiapplication/extendstaterestoration()
#app-main)
- UIKit
- UIApplication
- extendStateRestoration()
Instance Method
extendStateRestoration()
Tells the app that your code is restoring state asynchronously.
tvOS
@MainActor func extendStateRestoration()
Discussion
UIKit restores your app’s state synchronously on the main thread. If you choose to perform additional state restoration on a secondary thread, call this method to inform UIKit of that fact. You must balance each call to this method with a matching call to the completeStateRestoration() method.
Calling this method is a safety precaution in the event that your app crashes at launch time due to problems restoring its state. If you call this method but do not call the matching completeStateRestoration() method before a crash occurs, the system throws away any saved state information. Doing so prevents your app from crashing during subsequent launches because of issues caused by trying to restore your app’s state.
See Also
Managing state restoration
func completeStateRestoration()
Tells the app that your code has finished any asynchronous state restoration.
func ignoreSnapshotOnNextApplicationLaunch()
Prevents the app from using the recent snapshot image during the next launch cycle.
class func registerObject(forStateRestoration: any UIStateRestoring, restorationIdentifier: String)
Registers a custom object for use with the state restoration system.
https://developer.apple.com/documentation/uikit/uiapplication/completestaterestoration()
#app-main)
- UIKit
- UIApplication
- completeStateRestoration()
Instance Method
completeStateRestoration()
Tells the app that your code has finished any asynchronous state restoration.
tvOS
@MainActor func completeStateRestoration()
Discussion
UIKit restores your app’s state synchronously on the main thread. If you choose to perform additional state restoration on a secondary thread, call the extendStateRestoration() method to inform UIKit of that fact. Call this method after you finish with your background work to let the system know that state restoration is complete.
See Also
Managing state restoration
func extendStateRestoration()
Tells the app that your code is restoring state asynchronously.
func ignoreSnapshotOnNextApplicationLaunch()
Prevents the app from using the recent snapshot image during the next launch cycle.
class func registerObject(forStateRestoration: any UIStateRestoring, restorationIdentifier: String)
Registers a custom object for use with the state restoration system.
https://developer.apple.com/documentation/uikit/uiapplication/ignoresnapshotonnextapplicationlaunch()
#app-main)
- UIKit
- UIApplication
- ignoreSnapshotOnNextApplicationLaunch()
Instance Method
ignoreSnapshotOnNextApplicationLaunch()
Prevents the app from using the recent snapshot image during the next launch cycle.
tvOS
@MainActor func ignoreSnapshotOnNextApplicationLaunch()
Discussion
As part of the state preservation process, UIKit captures your app’s user interface and stores it in an image file. When your app is relaunched, the system displays this snapshot image in place of your app’s default launch image to preserve the notion that your app was still running. If you feel that the snapshot cannot correctly reflect your app’s user interface when your app is relaunched, call this method to let UIKit know that it should use your app’s default launch image instead of the snapshot.
You must call this method from within the code you use to preserve your app’s state.
See Also
Managing state restoration
func extendStateRestoration()
Tells the app that your code is restoring state asynchronously.
func completeStateRestoration()
Tells the app that your code has finished any asynchronous state restoration.
class func registerObject(forStateRestoration: any UIStateRestoring, restorationIdentifier: String)
Registers a custom object for use with the state restoration system.
https://developer.apple.com/documentation/uikit/uiapplication/registerobject(forstaterestoration:restorationidentifier:)
#app-main)
- UIKit
- UIApplication
- registerObject(forStateRestoration:restorationIdentifier:)
Type Method
registerObject(forStateRestoration:restorationIdentifier:)
Registers a custom object for use with the state restoration system.
tvOS
@MainActor class func registerObject( forStateRestoration object: any UIStateRestoring, restorationIdentifier: String )
Parameters
object
The object to be registered with the restoration archive. The object must adopt the UIStateRestoring protocol. This parameter must not be nil.
restorationIdentifier
The restoration identifier for the object. UIKit uses this parameter to distinguish the object from other objects in the archive. This parameter must not be nil.
Mentioned in
About the UI preservation process
Discussion
You use this method to register objects that you want to save as part of the overall state restoration process. Registering the object makes it available for inclusion in the restoration archive but does not automatically include it. To include the object, refer to it from one of your other interface objects. For example, you might write out a reference to the object from the encodeRestorableState(with:) method of one of your view controllers.
See Also
Managing state restoration
func extendStateRestoration()
Tells the app that your code is restoring state asynchronously.
func completeStateRestoration()
Tells the app that your code has finished any asynchronous state restoration.
func ignoreSnapshotOnNextApplicationLaunch()
Prevents the app from using the recent snapshot image during the next launch cycle.
https://developer.apple.com/documentation/uikit/uiapplication/isprotecteddataavailable
- UIKit
- UIApplication
- isProtectedDataAvailable
Instance Property
isProtectedDataAvailable
A Boolean value that indicates whether content protection is active.
tvOS
nonisolated var isProtectedDataAvailable: Bool { get }
Discussion
The value of this property is false if data protection is enabled and the device is currently locked. The value of this property is set to true if the device is unlocked or if content protection is not enabled.
When the value of this property is false, files that were assigned the complete or completeUnlessOpen protection key cannot be read or written by your app. The user must unlock the device before your app can access them.
See Also
Accessing protected content
class let protectedDataDidBecomeAvailableNotification: NSNotification.Name
A notification that posts when the protected files become available for your code to access.
class let protectedDataWillBecomeUnavailableNotification: NSNotification.Name
A notification that posts shortly before protected files are locked down and become inaccessible.
https://developer.apple.com/documentation/uikit/uiapplication/protecteddatadidbecomeavailablenotification
- UIKit
- UIApplication
- protectedDataDidBecomeAvailableNotification
Type Property
protectedDataDidBecomeAvailableNotification
A notification that posts when the protected files become available for your code to access.
tvOS
nonisolated class let protectedDataDidBecomeAvailableNotification: NSNotification.Name
Discussion
This notification does not contain a userInfo dictionary.
See Also
Accessing protected content
var isProtectedDataAvailable: Bool
A Boolean value that indicates whether content protection is active.
class let protectedDataWillBecomeUnavailableNotification: NSNotification.Name
A notification that posts shortly before protected files are locked down and become inaccessible.
https://developer.apple.com/documentation/uikit/uiapplication/protecteddatawillbecomeunavailablenotification
- UIKit
- UIApplication
- protectedDataWillBecomeUnavailableNotification
Type Property
protectedDataWillBecomeUnavailableNotification
A notification that posts shortly before protected files are locked down and become inaccessible.
tvOS
nonisolated class let protectedDataWillBecomeUnavailableNotification: NSNotification.Name
Discussion
Upon receiving this notification, clients should release any references to protected files. This notification does not contain a userInfo dictionary.
See Also
Accessing protected content
var isProtectedDataAvailable: Bool
A Boolean value that indicates whether content protection is active.
class let protectedDataDidBecomeAvailableNotification: NSNotification.Name
A notification that posts when the protected files become available for your code to access.
https://developer.apple.com/documentation/uikit/uiapplication/userinterfacelayoutdirection
- UIKit
- UIApplication
- userInterfaceLayoutDirection
Instance Property
userInterfaceLayoutDirection
The layout direction of the user interface.
tvOS
@MainActor var userInterfaceLayoutDirection: UIUserInterfaceLayoutDirection { get }
Discussion
This method specifies the general user interface layout flow direction. See UIUserInterfaceLayoutDirection for a description of the constants returned by this property.
See Also
Accessing the layout direction
enum UIUserInterfaceLayoutDirection
Constants that specify the directional flow of the user interface.
https://developer.apple.com/documentation/uikit/uiuserinterfacelayoutdirection
- UIKit
- UIUserInterfaceLayoutDirection
Enumeration
UIUserInterfaceLayoutDirection
Constants that specify the directional flow of the user interface.
tvOS
enum UIUserInterfaceLayoutDirection
Overview
One of these constants is returned by the userInterfaceLayoutDirection property. It indicates the directionality of the language in the user interface of the app.
Topics
Constants
case leftToRight
The layout direction is left to right.
case rightToLeft
The layout direction right to left.
Initializers
init?(rawValue: Int)
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Accessing the layout direction
var userInterfaceLayoutDirection: UIUserInterfaceLayoutDirection
The layout direction of the user interface.
https://developer.apple.com/documentation/uikit/uiapplication/supportsalternateicons
- UIKit
- UIApplication
- supportsAlternateIcons
Instance Property
supportsAlternateIcons
A Boolean value that indicates whether the app is allowed to change its icon.
@MainActor var supportsAlternateIcons: Bool { get }
Discussion
The value of this property is true only when the system allows you to change the icon of your app. To declare your app’s alternate icons, include them in the CFBundleIcons key of your app’s Info.plist file.
The value of this property is always false for apps built using the visionOS SDK.
See Also
Managing the app’s icon
var alternateIconName: String?
The name of the icon the system displays for the app.
Changes the icon the system displays for the app.
https://developer.apple.com/documentation/uikit/uiapplication/alternateiconname
- UIKit
- UIApplication
- alternateIconName
Instance Property
alternateIconName
The name of the icon the system displays for the app.
@MainActor var alternateIconName: String? { get }
Discussion
When the system is displaying one of your app’s alternate icons, the value of this property is the name of the alternate icon (from your app’s Info.plist file). When the system is displaying your app’s primary icon, the value of this property is nil.
See Also
Managing the app’s icon
var supportsAlternateIcons: Bool
A Boolean value that indicates whether the app is allowed to change its icon.
Changes the icon the system displays for the app.
https://developer.apple.com/documentation/uikit/uiapplication/setalternateiconname(_:completionhandler:)
#app-main)
- UIKit
- UIApplication
- setAlternateIconName(_:completionHandler:)
Instance Method
setAlternateIconName(_:completionHandler:)
Changes the icon the system displays for the app.
@MainActor func setAlternateIconName( _ alternateIconName: String?,
) @MainActor func setAlternateIconName(_ alternateIconName: String?) async throws
Parameters
alternateIconName
The name of the alternate icon, as declared in the CFBundleAlternateIcons key of your app’s Info.plist file. Specify nil if you want to display the app’s primary icon, which you declare using the CFBundlePrimaryIcon key. Both keys are subentries of the CFBundleIcons key in your app’s Info.plist file.
completionHandler
The handler to execute with the results. After attempting to change your app’s icon, the system reports the results by calling your handler. The handler executes on a UIKit-provided queue, and not necessarily on your app’s main queue. The handler has no return value and takes the following parameter:
error
On success, the value of this parameter is nil. If an error occurred, this parameter contains the error object indicating what happened and the value of the alternateIconName property remains unchanged.
Discussion
Use this method to change your app’s icon to its primary icon or to one of its alternate icons. You can change the icon only if the value of the supportsAlternateIcons property is true.
You must configure your app’s primary icon asset in the “App Icons and Launch Images” section of the General pane or set it directly using the “Primary App Icon Set Name” build setting. You specify the names of additional icon assets available to your app using the “Alternate App Icon Sets” build setting. Xcode uses these setting to generate the entries for CFBundlePrimaryIcon and CFBundleAlternateIcons under the top-level key CFBundleIcons. For more information, see Build settings reference and Configuring your app icon using an asset catalog.
See Also
Managing the app’s icon
var supportsAlternateIcons: Bool
A Boolean value that indicates whether the app is allowed to change its icon.
var alternateIconName: String?
The name of the icon the system displays for the app.
https://developer.apple.com/documentation/uikit/uiapplication/preferredcontentsizecategory
- UIKit
- UIApplication
- preferredContentSizeCategory
Instance Property
preferredContentSizeCategory
The font sizing option preferred by the user.
tvOS
@MainActor var preferredContentSizeCategory: UIContentSizeCategory { get }
Discussion
Users can request that apps display fonts in a size that is larger or smaller than the normal font size defined by the system. For example, a user with a visual impairment might request a larger default font size to make it easier to read text. Font objects returned by the system automatically scale based on the user’s preference. You can use the value of this property to request a font object of the appropriate size.
When the value of this property changes, the app object sends a didChangeNotification notification so that observers can respond accordingly.
For a list of possible values, see Content Size Category Constants and Accessibility Content Size Category Constants.
See Also
Managing the preferred content size
struct UIContentSizeCategory
Constants that indicate the preferred size of your content.
protocol UIContentSizeCategoryAdjusting
A collection of methods that give controls an easy way to adopt automatic adjustment to content category changes.
static let didChangeNotification: NSNotification.Name
A notification that posts when the user changes the preferred content size setting.
static let newValueUserInfoKey: String
A key that reflects the new preferred content size.
https://developer.apple.com/documentation/uikit/uicontentsizecategory
- UIKit
- UIContentSizeCategory
Structure
UIContentSizeCategory
Constants that indicate the preferred size of your content.
tvOS
struct UIContentSizeCategory
Topics
Font sizes
static let unspecified: UIContentSizeCategory
An unspecified font size.
static let extraSmall: UIContentSizeCategory
An extra-small font.
static let small: UIContentSizeCategory
A small font.
static let medium: UIContentSizeCategory
A medium-sized font.
static let large: UIContentSizeCategory
A large font.
static let extraLarge: UIContentSizeCategory
An extra-large font.
static let extraExtraLarge: UIContentSizeCategory
A font that is larger than the extra-large font but smaller than the largest font size available.
static let extraExtraExtraLarge: UIContentSizeCategory
The largest font size.
Accessibility sizes
static let accessibilityMedium: UIContentSizeCategory
A medium font size that reflects the current accessibility settings.
static let accessibilityLarge: UIContentSizeCategory
A large font size that reflects the current accessibility settings.
static let accessibilityExtraLarge: UIContentSizeCategory
An extra-large font size that reflects the current accessibility settings.
static let accessibilityExtraExtraLarge: UIContentSizeCategory
A font that is larger than the extra-large font but not the largest available, reflecting the current accessibility settings.
static let accessibilityExtraExtraExtraLarge: UIContentSizeCategory
The largest font size that reflects the current accessibility settings.
var isAccessibilityCategory: Bool
A Boolean value that indicates whether the content size category is associated with accessibility.
Font size change notifications
static let didChangeNotification: NSNotification.Name
A notification that posts when the user changes the preferred content size setting.
static let newValueUserInfoKey: String
A key that reflects the new preferred content size.
Font size category creation
init(rawValue: String)
Creates a new instance with the specified raw value.
init(ContentSizeCategory?)
Creates a content size category from the specified SwiftUI content size category.
init(DynamicTypeSize?)
Creates a content size category from the specified SwiftUI Dynamic Type size.
Structures
struct DidChangeMessage Beta
Relationships
Conforms To
ComparableCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Managing the preferred content size
var preferredContentSizeCategory: UIContentSizeCategory
The font sizing option preferred by the user.
protocol UIContentSizeCategoryAdjusting
A collection of methods that give controls an easy way to adopt automatic adjustment to content category changes.
https://developer.apple.com/documentation/uikit/uicontentsizecategoryadjusting
- UIKit
- UIContentSizeCategoryAdjusting
Protocol
UIContentSizeCategoryAdjusting
A collection of methods that give controls an easy way to adopt automatic adjustment to content category changes.
@MainActor protocol UIContentSizeCategoryAdjusting : NSObjectProtocol
Topics
Adjusting the size of fonts
var adjustsFontForContentSizeCategory: Bool
A Boolean that indicates whether the object automatically updates its font when the device’s content size category changes.
Required
Relationships
Inherits From
NSObjectProtocol
Conforming Types
UILabelUISearchTextFieldUITextFieldUITextView
See Also
Managing the preferred content size
var preferredContentSizeCategory: UIContentSizeCategory
The font sizing option preferred by the user.
struct UIContentSizeCategory
Constants that indicate the preferred size of your content.
static let didChangeNotification: NSNotification.Name
A notification that posts when the user changes the preferred content size setting.
static let newValueUserInfoKey: String
A key that reflects the new preferred content size.
https://developer.apple.com/documentation/uikit/uicontentsizecategory/didchangenotification
- UIKit
- UIContentSizeCategory
- didChangeNotification
Type Property
didChangeNotification
A notification that posts when the user changes the preferred content size setting.
tvOS
nonisolated static let didChangeNotification: NSNotification.Name
Mentioned in
Scaling Fonts Automatically
Discussion
This notification is sent when the value in the preferredContentSizeCategory property changes. The userInfo dictionary of the notification contains the newValueUserInfoKey key, which reflects the new setting.
See Also
Managing the preferred content size
var preferredContentSizeCategory: UIContentSizeCategory
The font sizing option preferred by the user.
struct UIContentSizeCategory
Constants that indicate the preferred size of your content.
protocol UIContentSizeCategoryAdjusting
A collection of methods that give controls an easy way to adopt automatic adjustment to content category changes.
static let newValueUserInfoKey: String
A key that reflects the new preferred content size.
https://developer.apple.com/documentation/uikit/uicontentsizecategory/newvalueuserinfokey
- UIKit
- UIContentSizeCategory
- newValueUserInfoKey
Type Property
newValueUserInfoKey
A key that reflects the new preferred content size.
tvOS
nonisolated static let newValueUserInfoKey: String
Discussion
This key’s value is an NSString object that reflects the new value of the preferredContentSizeCategory property.
See Also
Managing the preferred content size
var preferredContentSizeCategory: UIContentSizeCategory
The font sizing option preferred by the user.
struct UIContentSizeCategory
Constants that indicate the preferred size of your content.
protocol UIContentSizeCategoryAdjusting
A collection of methods that give controls an easy way to adopt automatic adjustment to content category changes.
static let didChangeNotification: NSNotification.Name
A notification that posts when the user changes the preferred content size setting.
https://developer.apple.com/documentation/uikit/uiapplication/supportedinterfaceorientations(for:)
#app-main)
- UIKit
- UIApplication
- supportedInterfaceOrientations(for:)
Instance Method
supportedInterfaceOrientations(for:)
Returns the default set of interface orientations to use for the view controllers in the specified window.
@MainActor
Parameters
window
The window whose default interface orientations you want to retrieve.
Return Value
A bit mask specifying which orientations are supported. See UIInterfaceOrientationMask for valid bit-mask values. The value returned by this method must not be 0.
Discussion
Starting in iOS 8, you should employ the UITraitCollection and UITraitEnvironment APIs, and size class properties as used in those APIs, instead of using this method or otherwise writing your app in terms of interface orientation.
This method returns the default interface orientations for the app. These orientations are used only for view controllers that do not specify their own. If your app delegate implements the application(_:supportedInterfaceOrientationsFor:) method, the system does not call this method.
The default implementation of this method returns the app’s default set of supported interface orientations, as you define them in the UISupportedInterfaceOrientations key of the Info.plist file in your Xcode project. If the file does not contain that key, this method returns all interface orientations for the iPad idiom and returns all interface orientations except the portrait upside-down orientation for the iPhone idiom.
https://developer.apple.com/documentation/uikit/uiapplication/userdidtakescreenshotnotification
https://developer.apple.com/documentation/uikit/uiapplication/isdefault(_:)
#app-main)
- UIKit
- UIApplication
- isDefault(_:)
Instance Method
isDefault(_:)
Reports whether this app is the person’s default app in the given category.
nonisolated
Parameters
category
The type of app for which you test whether your app is the default.
Return Value
If the system determines the status of the app, this method returns true if the app is the default app in the category, and false otherwise. If the system doesn’t determine the status, or the app exceeds the threshold rate for calling this method, it throws an error.
Discussion
To reduce the likelihood that users face continuous requests to set a browser as their default, this API only tells the browser app if it’s the default up to four times in a year. If you call the method too frequently, it throws an error with the domain UIApplicationCategoryDefaultErrorDomain and the code rateLimited. The error’s user information dictionary contains these keys:
statusLastProvidedDateErrorKey
The date at which the app most recently received a true or false response from this method.
retryAvailableDateErrorKey
The date at which the app can next request an updated response.
See Also
Discovering if your app is the default app in a category
enum Category
Constants that describe the types of apps in the system.
struct CategoryDefaultError
Errors that can happen when the system checks if your app is the default app in a category.
https://developer.apple.com/documentation/uikit/uiapplication/category
- UIKit
- UIApplication
- UIApplication.Category
Enumeration
UIApplication.Category
Constants that describe the types of apps in the system.
enum Category
Overview
Use the values in this enumeration with isDefault(_:) (or, in Objective-C, defaultStatusForCategory:error:) to find if your app is the person’s default for a category.
Topics
Application categories
case webBrowser
The app is a web browser.
Initializers
init?(rawValue: Int)
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Discovering if your app is the default app in a category
Reports whether this app is the person’s default app in the given category.
struct CategoryDefaultError
Errors that can happen when the system checks if your app is the default app in a category.
https://developer.apple.com/documentation/uikit/uiapplication/categorydefaulterror
- UIKit
- UIApplication
- UIApplication.CategoryDefaultError
Structure
UIApplication.CategoryDefaultError
Errors that can happen when the system checks if your app is the default app in a category.
struct CategoryDefaultError
Topics
Getting information about the error
enum Code
An enumeration of reasons an error happens when the system discovers whether your app is the default in a category.
static let retryAvailableDateErrorKey: String
A dictionary key, with a value that’s a date when a result is next available.
static let statusLastProvidedDateErrorKey: String
A dictionary key, with a value that’s the date your app last received a successful result.
Errors when discovering if an app is the default in a category
static var errorDomain: String
A string that indicates that an error happened when the system attempted to determine if your app is the default in a category.
static var rateLimited: UIApplication.CategoryDefaultError.Code
An error code that indicates your app requested its status too frequently.
Relationships
Conforms To
CustomNSErrorEquatableErrorHashableSendableSendableMetatype
See Also
Discovering if your app is the default app in a category
Reports whether this app is the person’s default app in the given category.
enum Category
Constants that describe the types of apps in the system.
https://developer.apple.com/documentation/uikit/uiapplication-deprecated-symbols
Collection
- UIKit
- App and environment
- UIApplication
- Deprecated symbols
API Collection
Deprecated symbols
Review unsupported symbols and their replacements.
Topics
Deprecated methods
Asks the system to activate an existing scene, or create a new scene and associate it with your app.
Deprecated
func beginIgnoringInteractionEvents()
Tells the receiver to suspend the handling of touch-related events.
func endIgnoringInteractionEvents()
Tells the receiver to resume the handling of touch-related events.
func setMinimumBackgroundFetchInterval(TimeInterval)
Specifies the minimum amount of time that must elapse between background fetch operations.
func scheduleLocalNotification(UILocalNotification)
Schedules a local notification for delivery at its encapsulated date and time.
func presentLocalNotificationNow(UILocalNotification)
Presents a local notification immediately.
func cancelLocalNotification(UILocalNotification)
Cancels the delivery of the specified scheduled local notification.
func cancelAllLocalNotifications()
Cancels the delivery of all scheduled local notifications.
Configures a periodic handler for VoIP apps in older versions of iOS.
let UIMinimumKeepAliveTimeout: TimeInterval
The minimum amount of time (measured in seconds) an app may run a critical background task in the background.
func clearKeepAliveTimeout()
Removes a previously installed periodic handler block.
func setStatusBarHidden(Bool, with: UIStatusBarAnimation)
Hides or shows the status bar, optionally animating the transition.
func setStatusBarStyle(UIStatusBarStyle, animated: Bool)
Sets the style of the status bar, optionally animating the transition to the new style.
func setStatusBarOrientation(UIInterfaceOrientation, animated: Bool)
Sets the app’s status bar to the specified orientation, optionally animating the transition.
func registerUserNotificationSettings(UIUserNotificationSettings)
Registers your preferred options for notifying the user.
func registerForRemoteNotifications(matching: UIRemoteNotificationType)
Register to receive remote notifications of the specified types via Apple Push Notification service.
Returns the types of notifications the app accepts.
struct UIRemoteNotificationType
Constants indicating the types of notifications the app may display to the user.
Attempts to open the resource at the specified URL.
func setNewsstandIconImage(UIImage?)
Sets the icon of a Newsstand app to an image depicting the current issue of a publication.
Deprecated notifications
class let willChangeStatusBarFrameNotification: NSNotification.Name
Posted when the app is about to change the frame of the status bar.
class let didChangeStatusBarFrameNotification: NSNotification.Name
Posted when the frame of the status bar changes.
class let willChangeStatusBarOrientationNotification: NSNotification.Name
Posted when the app is about to change the orientation of its interface.
class let didChangeStatusBarOrientationNotification: NSNotification.Name
Posted when the orientation of the app’s user interface changes.
Deprecated properties
var applicationIconBadgeNumber: Int
The number currently set as the badge of the app icon on the Home screen.
class let statusBarFrameUserInfoKey: String
A key whose value indicates the new status bar frame.
class let statusBarOrientationUserInfoKey: String
A key whose value indicates the current interface orientation.
var currentUserNotificationSettings: UIUserNotificationSettings?
Returns the user notification settings for the app.
var isIgnoringInteractionEvents: Bool
A Boolean value that indicates whether the receiver is ignoring events initiated by touches on the screen.
var isNetworkActivityIndicatorVisible: Bool
A Boolean value that turns an indicator of network activity on or off.
var isStatusBarHidden: Bool
A Boolean value that determines whether the status bar is hidden.
var keyWindow: UIWindow?
The app’s key window.
var scheduledLocalNotifications: [UILocalNotification]?
All currently scheduled local notifications.
var statusBarFrame: CGRect
The frame rectangle defining the area of the status bar.
var statusBarOrientation: UIInterfaceOrientation
The current orientation of the app’s status bar.
var statusBarOrientationAnimationDuration: TimeInterval
The animation duration in seconds for the status bar during a 90 degree orientation change.
var statusBarStyle: UIStatusBarStyle
The current style of the status bar.
The app’s visible and hidden windows.
https://developer.apple.com/documentation/uikit/uiapplication/backgroundrefreshstatusdidchangemessage
- UIKit
- UIApplication
- UIApplication.BackgroundRefreshStatusDidChangeMessage Beta
Structure
UIApplication.BackgroundRefreshStatusDidChangeMessage
struct BackgroundRefreshStatusDidChangeMessage
Topics
Initializers
init()
Relationships
Conforms To
NotificationCenter.MainActorMessageNotificationCenter.Message
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uiapplication/didbecomeactivemessage
- UIKit
- UIApplication
- UIApplication.DidBecomeActiveMessage Beta
Structure
UIApplication.DidBecomeActiveMessage
struct DidBecomeActiveMessage
Topics
Initializers
init()
Relationships
Conforms To
NotificationCenter.MainActorMessageNotificationCenter.Message
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uiapplication/didenterbackgroundmessage
- UIKit
- UIApplication
- UIApplication.DidEnterBackgroundMessage Beta
Structure
UIApplication.DidEnterBackgroundMessage
struct DidEnterBackgroundMessage
Topics
Initializers
init()
Relationships
Conforms To
NotificationCenter.MainActorMessageNotificationCenter.Message
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uiapplication/didfinishlaunchingmessage
- UIKit
- UIApplication
- UIApplication.DidFinishLaunchingMessage Beta
Structure
UIApplication.DidFinishLaunchingMessage
struct DidFinishLaunchingMessage
Topics
Initializers
init()
Relationships
Conforms To
NotificationCenter.MainActorMessageNotificationCenter.Message
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uiapplication/didreceivememorywarningmessage
- UIKit
- UIApplication
- UIApplication.DidReceiveMemoryWarningMessage Beta
Structure
UIApplication.DidReceiveMemoryWarningMessage
struct DidReceiveMemoryWarningMessage
Topics
Initializers
init()
Relationships
Conforms To
NotificationCenter.MainActorMessageNotificationCenter.Message
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uiapplication/protecteddatadidbecomeavailablemessage
- UIKit
- UIApplication
- UIApplication.ProtectedDataDidBecomeAvailableMessage Beta
Structure
UIApplication.ProtectedDataDidBecomeAvailableMessage
struct ProtectedDataDidBecomeAvailableMessage
Topics
Initializers
init()
Relationships
Conforms To
NotificationCenter.MainActorMessageNotificationCenter.Message
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uiapplication/protecteddatawillbecomeunavailablemessage
- UIKit
- UIApplication
- UIApplication.ProtectedDataWillBecomeUnavailableMessage Beta
Structure
UIApplication.ProtectedDataWillBecomeUnavailableMessage
struct ProtectedDataWillBecomeUnavailableMessage
Topics
Initializers
init()
Relationships
Conforms To
NotificationCenter.MainActorMessageNotificationCenter.Message
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uiapplication/significanttimechangemessage
https://developer.apple.com/documentation/uikit/uiapplication/userdidtakescreenshotmessage
- UIKit
- UIApplication
- UIApplication.UserDidTakeScreenshotMessage Beta
Structure
UIApplication.UserDidTakeScreenshotMessage
struct UserDidTakeScreenshotMessage
Topics
Initializers
init()
Relationships
Conforms To
NotificationCenter.MainActorMessageNotificationCenter.Message
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uiapplication/willenterforegroundmessage
- UIKit
- UIApplication
- UIApplication.WillEnterForegroundMessage Beta
Structure
UIApplication.WillEnterForegroundMessage
struct WillEnterForegroundMessage
Topics
Initializers
init()
Relationships
Conforms To
NotificationCenter.MainActorMessageNotificationCenter.Message
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uiapplication/willresignactivemessage
- UIKit
- UIApplication
- UIApplication.WillResignActiveMessage Beta
Structure
UIApplication.WillResignActiveMessage
struct WillResignActiveMessage
Topics
Initializers
init()
Relationships
Conforms To
NotificationCenter.MainActorMessageNotificationCenter.Message
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uiapplication/willterminatemessage
- UIKit
- UIApplication
- UIApplication.WillTerminateMessage Beta
Structure
UIApplication.WillTerminateMessage
struct WillTerminateMessage
Topics
Initializers
init()
Relationships
Conforms To
NotificationCenter.MainActorMessageNotificationCenter.Message
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uiresponder
- UIKit
- UIResponder
Class
UIResponder
An abstract interface for responding to and handling events.
tvOS
@MainActor class UIResponder
Mentioned in
Using responders and the responder chain to handle events
Handling key presses made on a physical keyboard
Overview
Responder objects — instances of UIResponder — constitute the event-handling backbone of a UIKit app. Many key objects are also responders, including the UIApplication object, UIViewController objects, and all UIView objects (which includes UIWindow). As events occur, UIKit dispatches them to your app’s responder objects for handling.
There are several kinds of events, including touch events, motion events, remote-control events, and press events. To handle a specific type of event, a responder must override the corresponding methods. For example, to handle touch events, a responder implements the touchesBegan(_:with:), touchesMoved(_:with:), touchesEnded(_:with:), and touchesCancelled(_:with:) methods. In the case of touches, the responder uses the event information provided by UIKit to track changes to those touches and to update the app’s interface appropriately.
In addition to handling events, UIKit responders also manage the forwarding of unhandled events to other parts of your app. If a given responder doesn’t handle an event, it forwards that event to the next event in the responder chain. UIKit manages the responder chain dynamically, using predefined rules to determine which object should be next to receive an event. For example, a view forwards events to its superview, and the root view of a hierarchy forwards events to its view controller.
Responders process UIEvent objects but can also accept custom input through an input view. The system’s keyboard is the most obvious example of an input view. When the user taps a UITextField and UITextView object onscreen, the view becomes the first responder and displays its input view, which is the system keyboard. Similarly, you can create custom input views and display them when other responders become active. To associate a custom input view with a responder, assign that view to the inputView property of the responder.
For information about responders and the responder chain, see Using responders and the responder chain to handle events.
Topics
Managing the responder chain
var next: UIResponder?
Returns the next responder in the responder chain, or nil if there’s no next responder.
var isFirstResponder: Bool
Returns a Boolean value indicating whether this object is the first responder.
var canBecomeFirstResponder: Bool
Returns a Boolean value indicating whether this object can become the first responder.
Asks UIKit to make this object the first responder in its window.
var canResignFirstResponder: Bool
Returns a Boolean value indicating whether the responder is willing to relinquish first-responder status.
Notifies this object that it has been asked to relinquish its status as first responder in its window.
Responding to touch events
Tells this object that one or more new touches occurred in a view or window.
Tells the responder when one or more touches associated with an event changed.
Tells the responder when one or more fingers are raised from a view or window.
Tells the responder when a system event (such as a system alert) cancels a touch sequence.
Tells the responder that updated values were received for previously estimated properties or that an update is no longer expected.
Responding to motion events
func motionBegan(UIEvent.EventSubtype, with: UIEvent?)
Tells the responder that a motion event has begun.
func motionEnded(UIEvent.EventSubtype, with: UIEvent?)
Tells the responder that a motion event has ended.
func motionCancelled(UIEvent.EventSubtype, with: UIEvent?)
Tells the responder that a motion event has been canceled.
Responding to press events
Generally, responders that handle press events should override all four of these methods.
Tells this object when a physical button is first pressed.
Tells this object when a value associated with a press has changed.
Tells the object when a button is released.
Tells this object when a system event (such as a low-memory warning) cancels a press event.
Responding to remote-control events
func remoteControlReceived(with: UIEvent?)
Tells the object when a remote-control event is received.
Managing input views
var inputView: UIView?
The custom input view to display when the responder becomes the first responder.
var inputViewController: UIInputViewController?
The custom input view controller to use when the responder becomes the first responder.
var inputAccessoryView: UIView?
The custom input accessory view to display when the responder becomes the first responder.
var inputAccessoryViewController: UIInputViewController?
The custom input accessory view controller to display when the responder becomes the first responder.
func reloadInputViews()
Updates the custom input and accessory views when the object is the first responder.
Getting the undo manager
var undoManager: UndoManager?
Returns the nearest shared undo manager in the responder chain.
Building and validating commands
func buildMenu(with: any UIMenuBuilder)
Asks the receiving responder to add and remove items from a menu system.
func validate(UICommand)
Asks the receiving responder to validate the command.
Requests the receiving responder to enable or disable the specified command in the user interface.
Returns the target object that responds to an action.
Accessing the available key commands
var keyCommands: [UIKeyCommand]?
The key commands that trigger actions on this responder.
Managing the text input mode
var textInputMode: UITextInputMode?
The text input mode for this responder object.
var textInputContextIdentifier: String?
An identifier signifying that the responder should preserve its text input mode information.
class func clearTextInputContextIdentifier(String)
Clears text input mode information from the app’s user defaults.
var inputAssistantItem: UITextInputAssistantItem
The input assistant to use when configuring the keyboard’s shortcuts bar.
Supporting user activities
var userActivity: NSUserActivity?
An object encapsulating a user activity supported by this responder.
func restoreUserActivityState(NSUserActivity)
Restores the state needed to continue the given user activity.
func updateUserActivityState(NSUserActivity)
Updates the state of the given user activity.
Managing activity items
var activityItemsConfiguration: (any UIActivityItemsConfigurationReading)?
Accessing the editing interaction
var editingInteractionConfiguration: UIEditingInteractionConfiguration
enum UIEditingInteractionConfiguration
Capturing text from the camera
func captureTextFromCamera(Any?)
Starts scanning text using the device’s camera.
Managing the Touch Bar
Asks the receiving responder to create and configure a Touch Bar object.
var touchBar: NSTouchBar?
The Touch Bar object for the responder.
Constants
class let keyboardAnimationCurveUserInfoKey: String
A user info key to retrieve the animation curve that the system uses to animate the keyboard onto or off the screen.
class let keyboardAnimationDurationUserInfoKey: String
A user info key to retrieve the duration of the keyboard animation in seconds.
class let keyboardDidChangeFrameNotification: NSNotification.Name
A notification that posts immediately after a change in the keyboard’s frame.
class let keyboardDidHideNotification: NSNotification.Name
A notification that posts immediately after dismissing the keyboard.
class let keyboardDidShowNotification: NSNotification.Name
A notification that posts immediately after displaying the keyboard.
class let keyboardFrameBeginUserInfoKey: String
A user info key to retrieve the keyboard’s frame at the beginning of its animation.
class let keyboardFrameEndUserInfoKey: String
A user info key to retrieve the keyboard’s frame at the end of its animation.
class let keyboardIsLocalUserInfoKey: String
A user info key to retrieve a Boolean value that indicates whether the keyboard belongs to the current app.
class let keyboardWillChangeFrameNotification: NSNotification.Name
A notification that posts immediately prior to a change in the keyboard’s frame.
class let keyboardWillHideNotification: NSNotification.Name
A notification that posts immediately prior to dismissing the keyboard.
class let keyboardWillShowNotification: NSNotification.Name
A notification that posts immediately prior to displaying the keyboard.
Structures
struct KeyboardDidChangeFrameMessage Beta
struct KeyboardDidHideMessage Beta
struct KeyboardDidShowMessage Beta
struct KeyboardWillChangeFrameMessage Beta
struct KeyboardWillHideMessage Beta
struct KeyboardWillShowMessage Beta
Instance Properties
var pencilKitResponderState: PKResponderState
The PencilKit state associated with the responder object.
Beta
Instance Methods
Asks the responder for an element provider to fulfill the given focus-based deferred element. Check the identifier of the deferred element to identify which deferred element this is. By default, this returns nil. Return a non-nil provider to make this responder responsible for providing elements for this fulfillment of the deferred element.
Relationships
Inherits From
NSObject
Inherited By
UIAccessibilityElementUIApplicationUISceneUIViewUIViewController
Conforms To
CVarArgCopyableCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolNSTouchBarProviderSendableUIActivityItemsConfigurationProvidingUIPasteConfigurationSupportingUIResponderStandardEditActionsUIUserActivityRestoring
See Also
Essentials
Learn how to handle events that propagate through your app.
class UIEvent
An object that describes a single user interaction with your app.
https://developer.apple.com/documentation/uikit/uiactivityitemsconfigurationproviding
- UIKit
- UIActivityItemsConfigurationProviding
Protocol
UIActivityItemsConfigurationProviding
An interface that provides a source for shareable content to fulfill user requests to share current content.
protocol UIActivityItemsConfigurationProviding : NSObjectProtocol
Overview
The user can share content from your app in a number of ways:
-
Ask Siri to “share this” on an iOS device.
-
Click an
NSSharingServicePickerToolbarItemin the toolbar of an app built with Mac Catalyst. -
Start a
UIContextMenuInteractionby using Force Touch or a long press gesture.
When one of these interactions happens, the system asks your view controller for content to share. Supply multiple representations of the current content, such as a file, image, and URL.
Topics
Providing shareable content
var activityItemsConfiguration: (any UIActivityItemsConfigurationReading)?
An object or value that specifies items to share.
Required
Relationships
Inherits From
NSObjectProtocol
Conforming Types
UIAccessibilityElementUIActionSheetUIActivityIndicatorViewUIActivityViewControllerUIAlertControllerUIAlertViewUIApplicationUIBackgroundExtensionViewUIButtonUICalendarViewUICloudSharingControllerUICollectionReusableViewUICollectionViewUICollectionViewCellUICollectionViewControllerUICollectionViewListCellUIColorPickerViewControllerUIColorWellUIContentUnavailableViewUIControlUIDatePickerUIDocumentBrowserViewControllerUIDocumentMenuViewControllerUIDocumentPickerExtensionViewControllerUIDocumentPickerViewControllerUIDocumentViewControllerUIEventAttributionViewUIFontPickerViewControllerUIImagePickerControllerUIImageViewUIInputViewUIInputViewControllerUILabelUIListContentViewUINavigationBarUINavigationControllerUIPageControlUIPageViewControllerUIPasteControlUIPickerViewUIPopoverBackgroundViewUIProgressViewUIReferenceLibraryViewControllerUIRefreshControlUIResponderUISceneUIScrollViewUISearchBarUISearchContainerViewControllerUISearchControllerUISearchTextFieldUISegmentedControlUISliderUISplitViewControllerUIStackViewUIStandardTextCursorViewUIStepperUISwitchUITabBarUITabBarControllerUITableViewUITableViewCellUITableViewControllerUITableViewHeaderFooterViewUITextFieldUITextFormattingViewControllerUITextViewUIToolbarUIVideoEditorControllerUIViewUIViewControllerUIVisualEffectViewUIWebViewUIWindowUIWindowScene
See Also
Activities interface
Collaborating and sharing copies of your data
Share data and collaborate with people from your app.
class UIActivityViewController
A view controller that you use to offer standard services from your app.
class UIActivityItemProvider
A proxy for data that passes to an activity view controller.
protocol UIActivityItemSource
A set of methods that an activity view controller uses to retrieve the data items to act on.
class UIActivity
An abstract class that you subclass to implement app-specific services.
https://developer.apple.com/documentation/uikit/uiresponderstandardeditactions
https://developer.apple.com/documentation/uikit/using-responders-and-the-responder-chain-to-handle-events)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/about-the-app-launch-sequence)
https://developer.apple.com/documentation/uikit/about-the-ui-preservation-process)
https://developer.apple.com/documentation/uikit/uiapplication)).
https://developer.apple.com/documentation/uikit/uiapplication/shared).
https://developer.apple.com/documentation/uikit/uiwindow)
https://developer.apple.com/documentation/uikit/uiapplication/open(_:options:completionhandler:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/beginignoringinteractionevents()))
))#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/registerforremotenotifications()))
))#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/applicationsupportsshaketoedit))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/canopenurl(_:)))
https://developer.apple.com/documentation/uikit/uiapplication/beginbackgroundtask(expirationhandler:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/beginbackgroundtask(withname:expirationhandler:)))
))#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/schedulelocalnotification(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/cancellocalnotification(_:)))
))#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/beginreceivingremotecontrolevents())
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/endreceivingremotecontrolevents()))
))#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication).
https://developer.apple.com/documentation/uikit/uiapplication/sendevent(_:))
https://developer.apple.com/documentation/uikit/uiapplication/sendaction(_:to:from:for:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/shared)
https://developer.apple.com/documentation/uikit/uiapplication/delegate)
https://developer.apple.com/documentation/uikit/uiapplication/registerforremotenotifications())
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/unregisterforremotenotifications())
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/isregisteredforremotenotifications)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/applicationstate)
https://developer.apple.com/documentation/uikit/uiapplication/state)
https://developer.apple.com/documentation/uikit/uiapplication/supportsmultiplescenes)
https://developer.apple.com/documentation/uikit/uiapplication/connectedscenes)
https://developer.apple.com/documentation/uikit/uiapplication/opensessions)
https://developer.apple.com/documentation/uikit/uiapplication/activatescenesession(for:errorhandler:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/requestscenesessiondestruction(_:options:errorhandler:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/requestscenesessionrefresh(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiscenesessionactivationrequest-swift.struct)
https://developer.apple.com/documentation/uikit/uiscene/activationrequestoptions)
https://developer.apple.com/documentation/uikit/uiscenedestructionrequestoptions)
https://developer.apple.com/documentation/uikit/uiapplication/backgroundrefreshstatus)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uibackgroundrefreshstatus)
https://developer.apple.com/documentation/uikit/uiapplication/backgroundrefreshstatusdidchangenotification)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/beginbackgroundtask(withname:expirationhandler:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/endbackgroundtask(_:))
https://developer.apple.com/documentation/uikit/uibackgroundtaskidentifier)
https://developer.apple.com/documentation/uikit/uiapplication/backgroundtimeremaining)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/backgroundfetchintervalminimum)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/backgroundfetchintervalnever)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/canopenurl(_:))
https://developer.apple.com/documentation/uikit/uiapplication/openexternalurloptionskey)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/opensettingsurlstring)
https://developer.apple.com/documentation/uikit/uiapplication/opennotificationsettingsurlstring)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplicationopennotificationsettingsurlstring)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/opendefaultapplicationssettingsurlstring)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/isidletimerdisabled)
https://developer.apple.com/documentation/uikit/uiapplication/extendstaterestoration())
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/completestaterestoration())
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/ignoresnapshotonnextapplicationlaunch())
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/registerobject(forstaterestoration:restorationidentifier:))
https://developer.apple.com/documentation/uikit/uiapplication/shortcutitems)
https://developer.apple.com/documentation/uikit/uiapplication/isprotecteddataavailable)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/protecteddatadidbecomeavailablenotification)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/protecteddatawillbecomeunavailablenotification)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/endreceivingremotecontrolevents())
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/userinterfacelayoutdirection)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiuserinterfacelayoutdirection)
https://developer.apple.com/documentation/uikit/uiapplication/applicationsupportsshaketoedit)
https://developer.apple.com/documentation/uikit/uiapplication/supportsalternateicons)
https://developer.apple.com/documentation/uikit/uiapplication/alternateiconname)
https://developer.apple.com/documentation/uikit/uiapplication/setalternateiconname(_:completionhandler:))
https://developer.apple.com/documentation/uikit/uiapplication/preferredcontentsizecategory)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uicontentsizecategory)
https://developer.apple.com/documentation/uikit/uicontentsizecategoryadjusting)
https://developer.apple.com/documentation/uikit/uicontentsizecategory/didchangenotification)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uicontentsizecategory/newvalueuserinfokey)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/supportedinterfaceorientations(for:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/userdidtakescreenshotnotification)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/isdefault(_:))
https://developer.apple.com/documentation/uikit/uiapplication/category)
https://developer.apple.com/documentation/uikit/uiapplication/categorydefaulterror)
https://developer.apple.com/documentation/uikit/uiapplication-deprecated-symbols)
https://developer.apple.com/documentation/uikit/uiapplication/backgroundrefreshstatusdidchangemessage)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/didbecomeactivemessage)
https://developer.apple.com/documentation/uikit/uiapplication/didenterbackgroundmessage)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/didfinishlaunchingmessage)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/didreceivememorywarningmessage)
https://developer.apple.com/documentation/uikit/uiapplication/protecteddatadidbecomeavailablemessage)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/protecteddatawillbecomeunavailablemessage)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/significanttimechangemessage)
https://developer.apple.com/documentation/uikit/uiapplication/userdidtakescreenshotmessage)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/willenterforegroundmessage)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/willresignactivemessage)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiapplication/willterminatemessage)
https://developer.apple.com/documentation/uikit/uiresponder)
https://developer.apple.com/documentation/uikit/uiactivityitemsconfigurationproviding)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiresponderstandardeditactions)
https://developer.apple.com/documentation/uikit/customizing-drawings
https://developer.apple.com/documentation/uikit/implementing-a-multi-touch-app
- UIKit
- Touches, presses, and gestures
- Handling touches in your view
- Implementing a Multi-Touch app
Article
Implementing a Multi-Touch app
Learn how to create a simple app that handles multitouch input.
Overview
Consider the app shown in the following image, where a single main view that draws a gray circle at each touch location. When a touch ends, the circle disappears. When the user’s fingers move, the underlying circles move with them.
The creation of this app begins with the Single View app template in Xcode. This type of app has a single view controller whose view — in this case, a custom subclass of UIView called TouchableView — fills the screen. The view contains only a label initially, but the app programmatically adds subviews later. The following image shows the storyboard for the view controller.
Implement the TouchableView class
The TouchableView class overrides the inherited touchesBegan(_:with:), touchesMoved(_:with:), touchesEnded(_:with:), and touchesCancelled(_:with:) methods. These methods handle the creation and management of subviews that draw the gray circles at each touch location. Specifically, these methods do the following:
-
The
touchesBegan(_:with:)method creates a new subview at the location of each touch event. -
The
touchesMoved(_:with:)method updates the position of the subview associated with each touch. -
The
touchesEnded(_:with:)andtouchesCancelled(_:with:)methods remove the subview associated with each touch that ended.
The following code shows the main implementation of the TouchableView class and its touch handling methods. Each method iterates through the touches and performs the needed actions. The touchViews dictionary uses the UITouch objects as keys to retrieve the subviews the user is manipulating onscreen.
class TouchableView: UIView { var touchViews = UITouch:TouchSpotView
override init(frame: CGRect) { super.init(frame: frame) isMultipleTouchEnabled = true }
required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) isMultipleTouchEnabled = true }
for touch in touches { createViewForTouch(touch: touch) } }
for touch in touches { let view = viewForTouch(touch: touch) // Move the view to the new location. let newLocation = touch.location(in: self) view?.center = newLocation } }
for touch in touches { removeViewForTouch(touch: touch) } }
// Other methods. . . }
Several helper methods handle creation, management, and disposal of the subviews, as shown in the following code. The createViewForTouch method creates a new TouchSpotView object and adds it to the TouchableView object, animating the view to its full size. The removeViewForTouch method removes the corresponding subview and updates the class data structures. The viewForTouch method is a convenience method for retrieving the view associated with a given touch event.
func createViewForTouch( touch : UITouch ) { let newView = TouchSpotView() newView.bounds = CGRect(x: 0, y: 0, width: 1, height: 1) newView.center = touch.location(in: self)
// Add the view and animate it to a new size. addSubview(newView) UIView.animate(withDuration: 0.2) { newView.bounds.size = CGSize(width: 100, height: 100) }
// Save the views internally touchViews[touch] = newView }
return touchViews[touch] }
func removeViewForTouch (touch : UITouch ) { if let view = touchViews[touch] { view.removeFromSuperview() touchViews.removeValue(forKey: touch) } }
Implement the TouchSpotView class
The TouchSpotView class (shown in the following code) represents the custom subviews that draw the gray circles onscreen. TouchSpotView maintains its circular shape by setting the cornerRadius property of the layer each time its bounds property changes.
class TouchSpotView : UIView { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.lightGray }
// Update the corner radius when the bounds change. override var bounds: CGRect { get { return super.bounds } set(newBounds) { super.bounds = newBounds layer.cornerRadius = newBounds.size.width / 2.0 } } }
See Also
Advanced touch handling
Learn how to support high-precision touches in your app.
Create a smooth and responsive drawing experience using UIKit’s predictions for touch locations.
https://developer.apple.com/documentation/uikit/making-a-view-into-a-drag-source
- UIKit
- Drag and drop
- Making a view into a drag source
Article
Making a view into a drag source
Adopt drag interaction APIs to provide items for dragging.
Overview
By implementing a drag interaction delegate ( UIDragInteractionDelegate) for a view, you enable that view to function as a drag source in your app.
Enable a view as a drag source
Any instance or subclass of UIView can act as a drag source. Your first steps to make this happen are:
-
Create a drag interaction (a
UIDragInteractioninstance). -
Specify the drag interaction’s delegate (an object that conforms to the
UIDragInteractionDelegateprotocol). -
Add the interaction to the view’s
interactionsproperty.
Here’s how to do this using a custom helper method, which you’d typically call within a view controller’s viewDidLoad() method:
func customEnableDragging(on view: UIView, dragInteractionDelegate: UIDragInteractionDelegate) { let dragInteraction = UIDragInteraction(delegate: dragInteractionDelegate) view.addInteraction(dragInteraction) }
Create a drag item
A drag item encapsulates a source app’s promises for providing a variety of data representations for one model object.
To create a drag item, implement the dragInteraction(_:itemsForBeginning:) method in your drag interaction delegate, as shown here in a minimal form:
// Cast to NSString is required for NSItemProviderWriting support.
let stringItemProvider = NSItemProvider(object: "Hello World" as NSString)
return [
UIDragItem(itemProvider: stringItemProvider)
]
}
This implementation uses the init(object:) convenience initializer. When you instantiate a drag item, pass an object in your app’s native representation, or in the highest-fidelity representation you support. In general, ensure that the first element in the item provider’s registeredTypeIdentifiers array represents the highest-fidelity data your drag interaction delegate can deliver.
To add more data representations to a drag item, as you typically would in your app, add them in fidelity order, from highest to lowest. When adding representations, you have choices:
-
The best option for adding multiple data representations to a drag item, in many cases, is to adopt the
NSItemProviderWritingprotocol in your model class. Using this protocol, you place the code for providing multiple data representations within the model class. -
You can use the
registerObject(_:visibility:)method, or related methods, from theNSItemProviderclass, to explicitly register data representations.
Understand a drag source in context
In the dragInteraction(_:itemsForBeginning:) protocol method, your source app responds to a request from the system. This request is itself triggered by the user starting to drag an item in your app’s UI. The conversation between your app and the system proceeds as shown here:
The figure above depicts the steps for constructing a drag item, in context:
-
The user initiates a drag activity with a long press on a view in your app, followed by moving their finger while still touching the screen. The system instantiates a drag session (an object that conforms to the
UIDragSessionprotocol, not shown in the figure) for managing the drag activity. -
The system calls the drag interaction delegate’s
dragInteraction(_:itemsForBeginning:)protocol method. Your delegate returns one or more drag items. -
Finally, the system populates the drag session with your drag items, ready for the user to move the drag session to a destination.
See Also
Essentials
Understanding a drag item as a promise
Use drag items to convey data representation promises between a source app and a destination app.
Making a view into a drop destination
Adopt drop interaction APIs to selectively consume dragged content.
Adopting drag and drop in a custom view
Demonstrates how to enable drag and drop for a UIImageView instance.
Adopting drag and drop in a table view
Demonstrates how to enable and implement drag and drop for a table view.
https://developer.apple.com/documentation/uikit/uiview/clipstobounds
- UIKit
- UIView
- clipsToBounds
Instance Property
clipsToBounds
A Boolean value that determines whether subviews are confined to the bounds of the view.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor var clipsToBounds: Bool { get set }
Mentioned in
Using responders and the responder chain to handle events
Discussion
Setting this value to true causes subviews to be clipped to the bounds of the view. If set to false, subviews whose frames extend beyond the visible bounds of the view aren’t clipped.
The default value is false. Some subclasses of UIView, like UIScrollView, override the default value to true.
See Also
Configuring a view’s visual appearance
var backgroundColor: UIColor?
The view’s background color.
var isHidden: Bool
A Boolean value that determines whether the view is hidden.
var alpha: CGFloat
The view’s alpha value.
var isOpaque: Bool
A Boolean value that determines whether the view is opaque.
var tintColor: UIColor!
The first nondefault tint color value in the view’s hierarchy, ascending from and starting with the view itself.
var tintAdjustmentMode: UIView.TintAdjustmentMode
The first non-default tint adjustment mode value in the view’s hierarchy, ascending from and starting with the view itself.
var clearsContextBeforeDrawing: Bool
A Boolean value that determines whether the view’s bounds should be automatically cleared before drawing.
var mask: UIView?
An optional view whose alpha channel is used to mask a view’s content.
class var layerClass: AnyClass
Returns the class used to create the layer for instances of this class.
var layer: CALayer
The view’s Core Animation layer to use for rendering.
https://developer.apple.com/documentation/uikit/uiview/frame
- UIKit
- UIView
- frame
Instance Property
frame
The frame rectangle, which describes the view’s location and size in its superview’s coordinate system.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor var frame: CGRect { get set }
Discussion
This rectangle defines the size and position of the view in its superview’s coordinate system. Use this rectangle during layout operations to set the size and position the view. Setting this property changes the point specified by the center property and changes the size in the bounds rectangle accordingly. The coordinates of the frame rectangle are always specified in points.
Changing the frame rectangle automatically redisplays the view without calling its draw(_:) method. If you want UIKit to call the draw(_:) method when the frame rectangle changes, set the contentMode property to UIView.ContentMode.redraw.
Changes to this property can be animated. However, if the transform property contains a non-identity transform, the value of the frame property is undefined and should not be modified. In that case, reposition the view using the center property and adjust the size using the bounds property instead.
See Also
Configuring the bounds and frame rectangles
var bounds: CGRect
The bounds rectangle, which describes the view’s location and size in its own coordinate system.
var center: CGPoint
The center point of the view’s frame rectangle.
var transform: CGAffineTransform
Specifies the transform applied to the view, relative to the center of its bounds.
var transform3D: CATransform3D
The three-dimensional transform to apply to the view.
var anchorPoint: CGPoint
The anchor point of the view’s bounds rectangle.
https://developer.apple.com/documentation/uikit/uiview/bounds
- UIKit
- UIView
- bounds
Instance Property
bounds
The bounds rectangle, which describes the view’s location and size in its own coordinate system.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor var bounds: CGRect { get set }
Mentioned in
Implementing a Multi-Touch app
Discussion
The default bounds origin is (0,0) and the size is the same as the size of the rectangle in the frame property. Changing the size portion of this rectangle grows or shrinks the view relative to its center point. Changing the size also changes the size of the rectangle in the frame property to match. The coordinates of the bounds rectangle are always specified in points.
Changing the bounds rectangle automatically redisplays the view without calling its draw(_:) method. If you want UIKit to call the draw(_:) method, set the contentMode property to UIView.ContentMode.redraw.
Changes to this property can be animated.
See Also
Configuring the bounds and frame rectangles
var frame: CGRect
The frame rectangle, which describes the view’s location and size in its superview’s coordinate system.
var center: CGPoint
The center point of the view’s frame rectangle.
var transform: CGAffineTransform
Specifies the transform applied to the view, relative to the center of its bounds.
var transform3D: CATransform3D
The three-dimensional transform to apply to the view.
var anchorPoint: CGPoint
The anchor point of the view’s bounds rectangle.
https://developer.apple.com/documentation/uikit/uiview/addsubview(_:)
#app-main)
- UIKit
- UIView
- addSubview(_:)
Instance Method
addSubview(_:)
Adds a view to the end of the receiver’s list of subviews.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor func addSubview(_ view: UIView)
Parameters
view
The view to be added. After being added, this view appears on top of any other subviews.
Discussion
This method establishes a strong reference to view and sets its next responder to the receiver, which is its new superview.
Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.
See Also
Managing the view hierarchy
var superview: UIView?
The receiver’s superview, or nil if it has none.
The receiver’s immediate subviews.
var window: UIWindow?
The receiver’s window object, or nil if it has none.
func bringSubviewToFront(UIView)
Moves the specified subview so that it appears on top of its siblings.
func sendSubviewToBack(UIView)
Moves the specified subview so that it appears behind its siblings.
func removeFromSuperview()
Unlinks the view from its superview and its window, and removes it from the responder chain.
func insertSubview(UIView, at: Int)
Inserts a subview at the specified index.
func insertSubview(UIView, aboveSubview: UIView)
Inserts a view above another view in the view hierarchy.
func insertSubview(UIView, belowSubview: UIView)
Inserts a view below another view in the view hierarchy.
func exchangeSubview(at: Int, withSubviewAt: Int)
Exchanges the subviews at the specified indices.
Returns a Boolean value indicating whether the receiver is a subview of a given view or identical to that view.
https://developer.apple.com/documentation/uikit/uiview/insertsubview(_:abovesubview:)
#app-main)
- UIKit
- UIView
- insertSubview(_:aboveSubview:)
Instance Method
insertSubview(_:aboveSubview:)
Inserts a view above another view in the view hierarchy.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor func insertSubview( _ view: UIView, aboveSubview siblingSubview: UIView )
Parameters
view
The view to insert. It’s removed from its superview if it’s not a sibling of siblingSubview.
siblingSubview
The sibling view that will be behind the inserted view.
Discussion
This method establishes a strong reference to view and sets its next responder to the receiver, which is its new superview.
Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.
See Also
Managing the view hierarchy
var superview: UIView?
The receiver’s superview, or nil if it has none.
The receiver’s immediate subviews.
var window: UIWindow?
The receiver’s window object, or nil if it has none.
func addSubview(UIView)
Adds a view to the end of the receiver’s list of subviews.
func bringSubviewToFront(UIView)
Moves the specified subview so that it appears on top of its siblings.
func sendSubviewToBack(UIView)
Moves the specified subview so that it appears behind its siblings.
func removeFromSuperview()
Unlinks the view from its superview and its window, and removes it from the responder chain.
func insertSubview(UIView, at: Int)
Inserts a subview at the specified index.
func insertSubview(UIView, belowSubview: UIView)
Inserts a view below another view in the view hierarchy.
func exchangeSubview(at: Int, withSubviewAt: Int)
Exchanges the subviews at the specified indices.
Returns a Boolean value indicating whether the receiver is a subview of a given view or identical to that view.
https://developer.apple.com/documentation/uikit/uiview/insertsubview(_:belowsubview:)
#app-main)
- UIKit
- UIView
- insertSubview(_:belowSubview:)
Instance Method
insertSubview(_:belowSubview:)
Inserts a view below another view in the view hierarchy.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor func insertSubview( _ view: UIView, belowSubview siblingSubview: UIView )
Parameters
view
The view to insert below another view. It’s removed from its superview if it’s not a sibling of siblingSubview.
siblingSubview
The sibling view that will be above the inserted view.
Discussion
This method establishes a strong reference to view and sets its next responder to the receiver, which is its new superview.
Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.
See Also
Managing the view hierarchy
var superview: UIView?
The receiver’s superview, or nil if it has none.
The receiver’s immediate subviews.
var window: UIWindow?
The receiver’s window object, or nil if it has none.
func addSubview(UIView)
Adds a view to the end of the receiver’s list of subviews.
func bringSubviewToFront(UIView)
Moves the specified subview so that it appears on top of its siblings.
func sendSubviewToBack(UIView)
Moves the specified subview so that it appears behind its siblings.
func removeFromSuperview()
Unlinks the view from its superview and its window, and removes it from the responder chain.
func insertSubview(UIView, at: Int)
Inserts a subview at the specified index.
func insertSubview(UIView, aboveSubview: UIView)
Inserts a view above another view in the view hierarchy.
func exchangeSubview(at: Int, withSubviewAt: Int)
Exchanges the subviews at the specified indices.
Returns a Boolean value indicating whether the receiver is a subview of a given view or identical to that view.
https://developer.apple.com/documentation/uikit/uiview/exchangesubview(at:withsubviewat:)
https://developer.apple.com/documentation/uikit/uiview/draw(_:)
#app-main)
- UIKit
- UIView
- draw(_:)
Instance Method
draw(_:)
Draws the view’s image within the passed-in rectangle.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor func draw(_ rect: CGRect)
Parameters
rect
The portion of the view’s bounds that needs to be updated. The first time your view is drawn, this rectangle is typically the entire visible bounds of your view. However, during subsequent drawing operations, the rectangle may specify only part of your view.
Discussion
The default implementation of this method does nothing. Subclasses that use technologies such as Core Graphics and UIKit to draw their view’s content should override this method and implement their drawing code there. You don’t need to override this method if your view sets its content in other ways. For example, you don’t need to override this method if your view just displays a background color or if your view sets its content directly using the underlying layer object.
By the time this method is called, UIKit has configured the drawing environment appropriately for your view and you can simply call whatever drawing methods and functions you need to render your content. Specifically, UIKit creates and configures a graphics context for drawing and adjusts the transform of that context so that its origin matches the origin of your view’s bounds rectangle. You can get a reference to the graphics context using the UIGraphicsGetCurrentContext() function, but don’t establish a strong reference to the graphics context because it can change between calls to the draw(_:) method.
Similarly, if you draw using OpenGL ES and the GLKView class, GLKit configures the underlying OpenGL ES context appropriately for your view before calling this method (or the glkView(_:drawIn:) method of your GLKView delegate), so you can simply issue whatever OpenGL ES commands you need to render your content. For more information about how to draw using OpenGL ES, see OpenGL ES Programming Guide.
You should limit any drawing to the rectangle specified in the rect parameter. In addition, if the isOpaque property of your view is set to true, your draw(_:) method must totally fill the specified rectangle with opaque content.
If you subclass UIView directly, your implementation of this method doesn’t need to call super. However, if you’re subclassing a different view class, you should call super at some point in your implementation.
This method is called when a view is first displayed or when an event occurs that invalidates a visible part of the view. You should never call this method directly yourself. To invalidate part of your view, and thus cause that portion to be redrawn, call the setNeedsDisplay() or setNeedsDisplay(_:) method instead.
In iOS 18 and later, UIKit supports automatic trait tracking inside this method for traits from this view’s traitCollection. For more information, see Automatic trait tracking.
See Also
Related Documentation
var contentMode: UIView.ContentMode
A flag used to determine how a view lays out its content when its bounds change.
Views
func updateProperties()
Override point for subclasses to update properties of this view. Never call this method directly; use setNeedsUpdateProperties to schedule an update.
Beta
func setNeedsUpdateProperties()
Call to manually request a properties update for the view. Multiple requests may be coalesced into a single update alongside the next layout pass.
func updatePropertiesIfNeeded()
Forces an immediate properties update for this view (and its view controller, if applicable) and any subviews, including any view controllers or views in its subtree.
func layoutSubviews()
Lays out subviews.
func updateConstraints()
Updates constraints for the view.
struct Properties
https://developer.apple.com/documentation/uikit/uiview/setneedsdisplay()
#app-main)
- UIKit
- UIView
- setNeedsDisplay()
Instance Method
setNeedsDisplay()
Marks the receiver’s entire bounds rectangle as needing to be redrawn.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor func setNeedsDisplay()
Discussion
You can use this method or the setNeedsDisplay(_:) to notify the system that your view’s contents need to be redrawn. This method makes a note of the request and returns immediately. The view is not actually redrawn until the next drawing cycle, at which point all invalidated views are updated.
You should use this method to request that a view be redrawn only when the content or appearance of the view change. If you simply change the geometry of the view, the view is typically not redrawn. Instead, its existing content is adjusted based on the value in the view’s contentMode property. Redisplaying the existing content improves performance by avoiding the need to redraw content that has not changed.
See Also
Related Documentation
var contentMode: UIView.ContentMode
A flag used to determine how a view lays out its content when its bounds change.
Drawing and updating the view
func draw(CGRect)
Draws the view’s image within the passed-in rectangle.
func setNeedsDisplay(CGRect)
Marks the specified rectangle of the receiver as needing to be redrawn.
var contentScaleFactor: CGFloat
The scale factor applied to the view.
func tintColorDidChange()
Called by the system when the tint color property changes.
https://developer.apple.com/documentation/uikit/uiview/setneedsdisplay(_:)
#app-main)
- UIKit
- UIView
- setNeedsDisplay(_:)
Instance Method
setNeedsDisplay(_:)
Marks the specified rectangle of the receiver as needing to be redrawn.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor func setNeedsDisplay(_ rect: CGRect)
Parameters
rect
The rectangular region of the receiver to mark as invalid; it should be specified in the coordinate system of the receiver.
Discussion
You can use this method or the setNeedsDisplay() to notify the system that your view’s contents need to be redrawn. This method adds the specified rectangle into the view’s current list of invalid rectangles and returns immediately. The view is not actually redrawn until the next drawing cycle, at which point all invalidated views are updated.
You should use this method to request that a view be redrawn only when the content or appearance of the view change. If you simply change the geometry of the view, the view is typically not redrawn. Instead, its existing content is adjusted based on the value in the view’s contentMode property. Redisplaying the existing content improves performance by avoiding the need to redraw content that has not changed.
See Also
Related Documentation
var contentMode: UIView.ContentMode
A flag used to determine how a view lays out its content when its bounds change.
Drawing and updating the view
func draw(CGRect)
Draws the view’s image within the passed-in rectangle.
func setNeedsDisplay()
Marks the receiver’s entire bounds rectangle as needing to be redrawn.
var contentScaleFactor: CGFloat
The scale factor applied to the view.
func tintColorDidChange()
Called by the system when the tint color property changes.
https://developer.apple.com/documentation/uikit/uiview/center
- UIKit
- UIView
- center
Instance Property
center
The center point of the view’s frame rectangle.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor var center: CGPoint { get set }
Discussion
The center point is specified in points in the coordinate system of its superview. Setting this property updates the origin of the rectangle in the frame property appropriately.
Use this property, instead of the frame property, when you want to change the position of a view. The center point is always valid, even when scaling or rotation factors are applied to the view’s transform. Changes to this property can be animated.
See Also
Configuring the bounds and frame rectangles
var frame: CGRect
The frame rectangle, which describes the view’s location and size in its superview’s coordinate system.
var bounds: CGRect
The bounds rectangle, which describes the view’s location and size in its own coordinate system.
var transform: CGAffineTransform
Specifies the transform applied to the view, relative to the center of its bounds.
var transform3D: CATransform3D
The three-dimensional transform to apply to the view.
var anchorPoint: CGPoint
The anchor point of the view’s bounds rectangle.
https://developer.apple.com/documentation/uikit/uiview/transform
- UIKit
- UIView
- transform
Instance Property
transform
Specifies the transform applied to the view, relative to the center of its bounds.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor var transform: CGAffineTransform { get set }
Discussion
Use this property to scale or rotate the view’s frame rectangle within its superview’s coordinate system. (To change the position of the view, modify the center property instead.) The default value of this property is CGAffineTransformIdentity.
Transformations occur relative to the view’s anchor point. By default, the anchor point is equal to the center point of the frame rectangle. To change the anchor point, modify the anchorPoint property of the view’s underlying CALayer object.
Changes to this property can be animated.
In iOS 8.0 and later, the transform property does not affect Auto Layout. Auto layout calculates a view’s alignment rectangle based on its untransformed frame.
See Also
Configuring the bounds and frame rectangles
var frame: CGRect
The frame rectangle, which describes the view’s location and size in its superview’s coordinate system.
var bounds: CGRect
The bounds rectangle, which describes the view’s location and size in its own coordinate system.
var center: CGPoint
The center point of the view’s frame rectangle.
var transform3D: CATransform3D
The three-dimensional transform to apply to the view.
var anchorPoint: CGPoint
The anchor point of the view’s bounds rectangle.
https://developer.apple.com/documentation/uikit/uiview/alpha
- UIKit
- UIView
- alpha
Instance Property
alpha
The view’s alpha value.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor var alpha: CGFloat { get set }
Mentioned in
Configuring the cells for your table
Discussion
The value of this property is a floating-point number in the range 0.0 to 1.0, where 0.0 represents totally transparent and 1.0 represents totally opaque. Changing the value of this property updates the alpha value of the current view only. However, the transparency imparted by that alpha value affects all of the view’s contents, including its subviews. For example, a subview with an alpha value of 1.0 that is embedded in a parent view with an alpha value of 0.5, appears onscreen as if its alpha value is also 0.5.
Changes to this property can be animated.
See Also
Configuring a view’s visual appearance
var backgroundColor: UIColor?
The view’s background color.
var isHidden: Bool
A Boolean value that determines whether the view is hidden.
var isOpaque: Bool
A Boolean value that determines whether the view is opaque.
var tintColor: UIColor!
The first nondefault tint color value in the view’s hierarchy, ascending from and starting with the view itself.
var tintAdjustmentMode: UIView.TintAdjustmentMode
The first non-default tint adjustment mode value in the view’s hierarchy, ascending from and starting with the view itself.
var clipsToBounds: Bool
A Boolean value that determines whether subviews are confined to the bounds of the view.
var clearsContextBeforeDrawing: Bool
A Boolean value that determines whether the view’s bounds should be automatically cleared before drawing.
var mask: UIView?
An optional view whose alpha channel is used to mask a view’s content.
class var layerClass: AnyClass
Returns the class used to create the layer for instances of this class.
var layer: CALayer
The view’s Core Animation layer to use for rendering.
https://developer.apple.com/documentation/uikit/uiview/backgroundcolor
- UIKit
- UIView
- backgroundColor
Instance Property
backgroundColor
The view’s background color.
iOSiPadOSMac CatalysttvOSvisionOS
@NSCopying @MainActor var backgroundColor: UIColor? { get set }
Discussion
Changes to this property can be animated. The default value is nil, which results in a transparent background color.
See Also
Configuring a view’s visual appearance
var isHidden: Bool
A Boolean value that determines whether the view is hidden.
var alpha: CGFloat
The view’s alpha value.
var isOpaque: Bool
A Boolean value that determines whether the view is opaque.
var tintColor: UIColor!
The first nondefault tint color value in the view’s hierarchy, ascending from and starting with the view itself.
var tintAdjustmentMode: UIView.TintAdjustmentMode
The first non-default tint adjustment mode value in the view’s hierarchy, ascending from and starting with the view itself.
var clipsToBounds: Bool
A Boolean value that determines whether subviews are confined to the bounds of the view.
var clearsContextBeforeDrawing: Bool
A Boolean value that determines whether the view’s bounds should be automatically cleared before drawing.
var mask: UIView?
An optional view whose alpha channel is used to mask a view’s content.
class var layerClass: AnyClass
Returns the class used to create the layer for instances of this class.
var layer: CALayer
The view’s Core Animation layer to use for rendering.
https://developer.apple.com/documentation/uikit/uiviewpropertyanimator
- UIKit
- UIViewPropertyAnimator
Class
UIViewPropertyAnimator
A class that animates changes to views and allows the dynamic modification of those animations.
@MainActor class UIViewPropertyAnimator
Overview
A UIViewPropertyAnimator object lets you animate changes to views and dynamically modify your animations before they finish. With a property animator, you can run your animations from start to finish normally or you can turn them into interactive animations and control the timing yourself. The animator operates on animatable properties of views, such as the frame, center, alpha, and transform properties, creating the needed animations from the blocks you provide.
When creating a property animator object, you specify the following:
-
A block containing code that modifies the properties of one or more views.
-
The timing curve that defines the speed of the animation over the course of its run.
-
The duration (in seconds) of the animation.
-
An optional completion block to execute when the animations finish.
In your animation blocks, set the value of an animatable property to the final value you want reflected by that view. For example, if you want to fade out a view, you would set its alpha property to 0 in your block. The property animator object creates an animation that adjusts the value of that property from its initial value to the new value that you specified in your block.
The speed at which the value of a property changes is controlled by the timing curve you specify when creating the property animator. Property animators include support for the built-in UIKit animation curves such as linear, ease-in, and ease-out. You can also use a cubic Bezier curve or a spring function to control the timing of the animations.
If you create your animator using one of the standard initialization methods, you must explicitly start your animations by calling the startAnimation() method. If you want to start the animations immediately after the creation of your animator, use the runningPropertyAnimator(withDuration:delay:options:animations:completion:) method instead of the standard initializers.
This class adopts the UIViewAnimating and UIViewImplicitlyAnimating protocols, which define the methods for starting, stopping, and modifying your animations. For more information about the methods of those protocols, see UIViewAnimating and UIViewImplicitlyAnimating.
Modify animations dynamically
A property animator gives you programmatic control over the timing and execution of the animations. Specifically, you can:
-
Start, pause, resume, and stop animations; see the methods of the
UIViewAnimatingprotocol. -
Add animation blocks after the original animations start using the
addAnimations(_:)andaddAnimations(_:delayFactor:)methods. -
Scrub through a paused animation by modifying the
fractionCompleteproperty. -
Change the animation’s direction using the
isReversedproperty. -
Modify the timing and duration of a partially complete animation by pausing the animation and using the
continueAnimation(withTimingParameters:durationFactor:)method to finish it.
Most of the basic behavior is controlled by the properties of the UIViewAnimating protocol, which this class adopts. Use those methods and properties to start, pause, resume, and stop the animations. You can also use them to scrub through the animation and change its direction. Use the methods and properties of this class to modify the animation blocks themselves and to update the timing information.
Topics
Initializing a property animator
Initializes the animator with a built-in UIKit timing curve.
Initializes the animator object with a cubic Bézier timing curve.
Initializes the animator object with spring-based timing information.
init(duration: TimeInterval, timingParameters: any UITimingCurveProvider)
Initializes the animator object with a custom timing curve object.
Creates and returns an animator object that begins running its animations immediately.
Modifying animations
Adds the specified animation block to the animator.
Adds the specified animation block with a delay.
Adds the specified completion block to the animator.
func continueAnimation(withTimingParameters: (any UITimingCurveProvider)?, durationFactor: CGFloat)
Adjusts the timing and duration of a paused animation.
Accessing the animation parameters
var duration: TimeInterval
The total duration (in seconds) of the main animations.
var delay: TimeInterval
The delay (in seconds) after which the animations begin.
var timingParameters: (any UITimingCurveProvider)?
The information used to determine the timing curve for the animation.
var isInterruptible: Bool
A Boolean value indicating whether the animator is interruptible and can be paused or stopped.
var isUserInteractionEnabled: Bool
A Boolean value indicating whether views receive touch events while animations are running.
var isManualHitTestingEnabled: Bool
A Boolean value indicating whether your app manages hit-testing while animations are in progress.
var scrubsLinearly: Bool
A Boolean value indicating whether a paused animation scrubs linearly or uses its specified timing information.
var pausesOnCompletion: Bool
A Boolean value that indicates whether a completed animation remains in the active state.
Instance Properties
var flushUpdates: Bool
Flush all pending updates (including traits, properties, and layout) whenever the animation context changes. This includes flushing updates:
Beta
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCopyingNSObjectProtocolSendableUIViewAnimatingUIViewImplicitlyAnimating
See Also
Essentials
protocol UIViewAnimating
An interface for implementing custom animator objects.
https://developer.apple.com/documentation/uikit/uiview/init(frame:)
#app-main)
- UIKit
- UIView
- init(frame:)
Initializer
init(frame:)
Creates a view with the specified frame rectangle.
tvOS
@MainActor init(frame: CGRect)
Parameters
frame
The frame rectangle for the view, measured in points. The origin of the frame is relative to the superview in which you plan to add it. This method uses the frame rectangle to set the center and bounds properties accordingly.
Return Value
An initialized view object.
Discussion
The new view object must be inserted into the view hierarchy of a window before it can be used. If you create a view object programmatically, this method is the designated initializer for the UIView class. Subclasses can override this method to perform any custom initialization but must call super at the beginning of their implementation.
If you use Interface Builder to design your interface, this method is not called when your view objects are subsequently loaded from the nib file. Objects in a nib file are reconstituted and then initialized using their doc://com.apple.documentation/documentation/oslog/oslogentry/init(coder:) method, which modifies the attributes of the view to match the attributes stored in the nib file. For detailed information about how views are loaded from a nib file, see Resource Programming Guide.
See Also
Creating a view object
init?(coder: NSCoder)
Creates a view from data in an unarchiver.
https://developer.apple.com/documentation/uikit/uiview/layerclass
- UIKit
- UIView
- layerClass
Type Property
layerClass
Returns the class used to create the layer for instances of this class.
tvOS
@MainActor class var layerClass: AnyClass { get }
Return Value
The class used to create the view’s Core Animation layer.
Discussion
This method returns the CALayer class object by default. Subclasses can override this method and return a different layer class as needed. For example, if your view uses tiling to display a large scrollable area, you might want to override this property and return the CATiledLayer class, as shown in the following code.
override class var layerClass : AnyClass { return CATiledLayer.self }
This method is called only once early in the creation of the view in order to create the corresponding layer object.
See Also
Configuring a view’s visual appearance
var backgroundColor: UIColor?
The view’s background color.
var isHidden: Bool
A Boolean value that determines whether the view is hidden.
var alpha: CGFloat
The view’s alpha value.
var isOpaque: Bool
A Boolean value that determines whether the view is opaque.
var tintColor: UIColor!
The first nondefault tint color value in the view’s hierarchy, ascending from and starting with the view itself.
var tintAdjustmentMode: UIView.TintAdjustmentMode
The first non-default tint adjustment mode value in the view’s hierarchy, ascending from and starting with the view itself.
var clipsToBounds: Bool
A Boolean value that determines whether subviews are confined to the bounds of the view.
var clearsContextBeforeDrawing: Bool
A Boolean value that determines whether the view’s bounds should be automatically cleared before drawing.
var mask: UIView?
An optional view whose alpha channel is used to mask a view’s content.
var layer: CALayer
The view’s Core Animation layer to use for rendering.
https://developer.apple.com/documentation/uikit/uiview/draw(_:for:)
#app-main)
- UIKit
- UIView
- draw(_:for:)
Instance Method
draw(_:for:)
Implemented to draw the view’s content for printing.
iOSiPadOSMac CatalystvisionOS
@MainActor func draw( _ rect: CGRect, for formatter: UIViewPrintFormatter )
Parameters
rect
A rectangle that defines the area for drawing printable content.
formatter
An instance of UIViewPrintFormatter obtained by calling the viewPrintFormatter() method.
Discussion
You implement this method if you want a view’s printed content to appear differently than its displayed content. If you add a view print formatter to a print job but do not implement this method, the view’s draw(_:) method is called to provide the content for printing.
For more information about how to implement a custom drawing routine for printed content, see Drawing and Printing Guide for iOS.
See Also
Formatting printed view content
Returns a print formatter for the receiving view.
https://developer.apple.com/documentation/uikit/uiview/requiresconstraintbasedlayout
- UIKit
- UIView
- requiresConstraintBasedLayout
Type Property
requiresConstraintBasedLayout
A Boolean value that indicates whether the receiver depends on the constraint-based layout system.
tvOS
@MainActor class var requiresConstraintBasedLayout: Bool { get }
Return Value
true if the view must be in a window using constraint-based layout to function properly, false otherwise.
Discussion
Custom views should override this to return true if they cannot layout correctly using autoresizing.
See Also
Laying out subviews
func layoutSubviews()
Lays out subviews.
func setNeedsLayout()
Invalidates the current layout of the receiver and triggers a layout update during the next update cycle.
func layoutIfNeeded()
Lays out the subviews immediately, if layout updates are pending.
var translatesAutoresizingMaskIntoConstraints: Bool
A Boolean value that determines whether the view’s autoresizing mask is translated into Auto Layout constraints.
https://developer.apple.com/documentation/uikit/uiview/updateconstraints()
#app-main)
- UIKit
- UIView
- updateConstraints()
Instance Method
updateConstraints()
Updates constraints for the view.
tvOS
@MainActor func updateConstraints()
Discussion
Override this method to optimize changes to your constraints.
To schedule a change, call setNeedsUpdateConstraints() on the view. The system then calls your implementation of updateConstraints() before the layout occurs. This lets you verify that all necessary constraints for your content are in place at a time when your custom view’s properties aren’t changing.
Your implementation must be as efficient as possible. Don’t deactivate all your constraints, then reactivate the ones you need. Instead, your app must have some way of tracking your constraints, and validating them during each update pass. Only change items that need to be changed. During each update pass, you must ensure that you have the appropriate constraints for the app’s current state.
Don’t call setNeedsUpdateConstraints() inside your implementation. Calling setNeedsUpdateConstraints() schedules another update pass, creating a feedback loop.
In iOS 18 and later, UIKit supports automatic trait tracking inside this method for traits from this view’s traitCollection. For more information, see Automatic trait tracking.
See Also
Views
func updateProperties()
Override point for subclasses to update properties of this view. Never call this method directly; use setNeedsUpdateProperties to schedule an update.
Beta
func setNeedsUpdateProperties()
Call to manually request a properties update for the view. Multiple requests may be coalesced into a single update alongside the next layout pass.
func updatePropertiesIfNeeded()
Forces an immediate properties update for this view (and its view controller, if applicable) and any subviews, including any view controllers or views in its subtree.
func layoutSubviews()
Lays out subviews.
func draw(CGRect)
Draws the view’s image within the passed-in rectangle.
struct Properties
https://developer.apple.com/documentation/uikit/uiview/alignmentrect(forframe:)
#app-main)
- UIKit
- UIView
- alignmentRect(forFrame:)
Instance Method
alignmentRect(forFrame:)
Returns the view’s alignment rectangle for a given frame.
tvOS
@MainActor
Parameters
frame
The frame whose corresponding alignment rectangle is desired.
Return Value
The alignment rectangle for the specified frame.
Discussion
The constraint-based layout system uses alignment rectangles to align views, rather than their frame. This allows custom views to be aligned based on the location of their content while still having a frame that encompasses any ornamentation they need to draw around their content, such as shadows or reflections.
The default implementation returns the view’s frame modified by the view’s alignmentRectInsets. Most custom views can use alignmentRectInsets to specify the location of their content within their frame. Custom views that require arbitrary transformations can override alignmentRect(forFrame:) and frame(forAlignmentRect:) to describe the location of their content. These two methods must always be inverses of each other.
See Also
Aligning views in Auto Layout
Returns the view’s frame for a given alignment rectangle.
var alignmentRectInsets: UIEdgeInsets
The insets from the view’s frame that define its alignment rectangle.
var forFirstBaselineLayout: UIView
Returns a view used to satisfy first baseline constraints.
var forLastBaselineLayout: UIView
Returns a view used to satisfy last baseline constraints.
https://developer.apple.com/documentation/uikit/uiview/frame(foralignmentrect:)
#app-main)
- UIKit
- UIView
- frame(forAlignmentRect:)
Instance Method
frame(forAlignmentRect:)
Returns the view’s frame for a given alignment rectangle.
tvOS
@MainActor
Parameters
alignmentRect
The alignment rectangle whose corresponding frame is desired.
Return Value
The frame for the specified alignment rectangle
Discussion
The constraint-based layout system uses alignment rectangles to align views, rather than their frame. This allows custom views to be aligned based on the location of their content while still having a frame that encompasses any ornamentation they need to draw around their content, such as shadows or reflections.
The default implementation returns alignmentRect modified by the view’s alignmentRectInsets. Most custom views can override alignmentRectInsets to specify the location of their content within their frame. Custom views that require arbitrary transformations can override alignmentRect(forFrame:) and frame(forAlignmentRect:) to describe the location of their content. These two methods must always be inverses of each other.
See Also
Aligning views in Auto Layout
Returns the view’s alignment rectangle for a given frame.
var alignmentRectInsets: UIEdgeInsets
The insets from the view’s frame that define its alignment rectangle.
var forFirstBaselineLayout: UIView
Returns a view used to satisfy first baseline constraints.
var forLastBaselineLayout: UIView
Returns a view used to satisfy last baseline constraints.
https://developer.apple.com/documentation/uikit/uiview/didaddsubview(_:)
#app-main)
- UIKit
- UIView
- didAddSubview(_:)
Instance Method
didAddSubview(_:)
Tells the view that a subview was added.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor func didAddSubview(_ subview: UIView)
Parameters
subview
The view that was added as a subview.
Discussion
The default implementation of this method does nothing. Subclasses can override it to perform additional actions when subviews are added. This method is called in response to adding a subview using any of the relevant view methods.
See Also
Related Documentation
func insertSubview(UIView, belowSubview: UIView)
Inserts a view below another view in the view hierarchy.
func insertSubview(UIView, aboveSubview: UIView)
Inserts a view above another view in the view hierarchy.
func addSubview(UIView)
Adds a view to the end of the receiver’s list of subviews.
func insertSubview(UIView, at: Int)
Inserts a subview at the specified index.
Observing view-related changes
func willRemoveSubview(UIView)
Tells the view that a subview is about to be removed.
func willMove(toSuperview: UIView?)
Tells the view that its superview is about to change to the specified superview.
func didMoveToSuperview()
Tells the view that its superview changed.
func willMove(toWindow: UIWindow?)
Tells the view that its window object is about to change.
func didMoveToWindow()
Tells the view that its window object changed.
https://developer.apple.com/documentation/uikit/uiview/willremovesubview(_:)
#app-main)
- UIKit
- UIView
- willRemoveSubview(_:)
Instance Method
willRemoveSubview(_:)
Tells the view that a subview is about to be removed.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor func willRemoveSubview(_ subview: UIView)
Parameters
subview
The subview that will be removed.
Discussion
The default implementation of this method does nothing. Subclasses can override it to perform additional actions whenever subviews are removed. This method is called when the subview’s superview changes or when the subview is removed from the view hierarchy completely.
See Also
Related Documentation
func removeFromSuperview()
Unlinks the view from its superview and its window, and removes it from the responder chain.
Observing view-related changes
func didAddSubview(UIView)
Tells the view that a subview was added.
func willMove(toSuperview: UIView?)
Tells the view that its superview is about to change to the specified superview.
func didMoveToSuperview()
Tells the view that its superview changed.
func willMove(toWindow: UIWindow?)
Tells the view that its window object is about to change.
func didMoveToWindow()
Tells the view that its window object changed.
https://developer.apple.com/documentation/uikit/uiview/willmove(tosuperview:)
#app-main)
- UIKit
- UIView
- willMove(toSuperview:)
Instance Method
willMove(toSuperview:)
Tells the view that its superview is about to change to the specified superview.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor func willMove(toSuperview newSuperview: UIView?)
Parameters
newSuperview
A view object that will be the new superview of the receiver. This object may be nil.
Discussion
The default implementation of this method does nothing. Subclasses can override it to perform additional actions whenever the superview changes.
See Also
Observing view-related changes
func didAddSubview(UIView)
Tells the view that a subview was added.
func willRemoveSubview(UIView)
Tells the view that a subview is about to be removed.
func didMoveToSuperview()
Tells the view that its superview changed.
func willMove(toWindow: UIWindow?)
Tells the view that its window object is about to change.
func didMoveToWindow()
Tells the view that its window object changed.
https://developer.apple.com/documentation/uikit/uiview/didmovetosuperview()
#app-main)
- UIKit
- UIView
- didMoveToSuperview()
Instance Method
didMoveToSuperview()
Tells the view that its superview changed.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor func didMoveToSuperview()
Discussion
The default implementation of this method does nothing. Subclasses can override it to perform additional actions whenever the superview changes.
See Also
Observing view-related changes
func didAddSubview(UIView)
Tells the view that a subview was added.
func willRemoveSubview(UIView)
Tells the view that a subview is about to be removed.
func willMove(toSuperview: UIView?)
Tells the view that its superview is about to change to the specified superview.
func willMove(toWindow: UIWindow?)
Tells the view that its window object is about to change.
func didMoveToWindow()
Tells the view that its window object changed.
https://developer.apple.com/documentation/uikit/uiview/gesturerecognizershouldbegin(_:)
#app-main)
- UIKit
- UIView
- gestureRecognizerShouldBegin(_:)
Instance Method
gestureRecognizerShouldBegin(_:)
Asks the view if the gesture recognizer should continue tracking touch events.
tvOS
@MainActor
Parameters
gestureRecognizer
The gesture recognizer that’s attempting to transition out of the UIGestureRecognizer.State.possible state.
Return Value
true if the gesture recognizer should continue tracking touch events and use them to trigger a gesture or false if it should transition to the UIGestureRecognizer.State.failed state.
Discussion
Subclasses may override this method and use it to prevent the recognition of particular gestures. For example, the UISlider class uses this method to prevent swipes parallel to the slider’s travel direction and that start in the thumb.
At the time this method is called, the gesture recognizer is in the UIGestureRecognizer.State.possible state and thinks it has the events needed to move to the UIGestureRecognizer.State.began state.
The default implementation of this method returns true.
See Also
Managing gesture recognizers
func addGestureRecognizer(UIGestureRecognizer)
Attaches a gesture recognizer to the view.
func removeGestureRecognizer(UIGestureRecognizer)
Detaches a gesture recognizer from the receiving view.
var gestureRecognizers: [UIGestureRecognizer]?
The gesture-recognizer objects currently attached to the view.
https://developer.apple.com/documentation/uikit/uiresponder/touchesbegan(_:with:)
https://developer.apple.com/documentation/uikit/uiresponder/touchesmoved(_:with:)
#app-main)
- UIKit
- UIResponder
- touchesMoved(_:with:)
Instance Method
touchesMoved(_:with:)
Tells the responder when one or more touches associated with an event changed.
tvOS
@MainActor func touchesMoved(
with event: UIEvent? )
Parameters
touches
A set of UITouch instances that represent the touches whose values changed. These touches all belong to the specified event. For touches in a view, this set contains only one touch by default. To receive multiple touches, you must set the view’s isMultipleTouchEnabled property to true.
event
The event to which the touches belong.
Mentioned in
Implementing a Multi-Touch app
Implementing a Continuous Gesture Recognizer
Implementing a Discrete Gesture Recognizer
Discussion
UIKit calls this method when the location or force of a touch changes. Many UIKit classes override this method and use it to handle the corresponding touch events. The default implementation of this method forwards the message up the responder chain. When creating your own subclasses, call super to forward any events that you don’t handle yourself, like in the following code.
super.touchesMoved(touches, with: event)
[super touchesMoved:touches withEvent:event];
If you override this method without calling super (a common use pattern), you must also override the other methods for handling touch events, even if your implementations do nothing.
See Also
Responding to touch events
Tells this object that one or more new touches occurred in a view or window.
Tells the responder when one or more fingers are raised from a view or window.
Tells the responder when a system event (such as a system alert) cancels a touch sequence.
Tells the responder that updated values were received for previously estimated properties or that an update is no longer expected.
https://developer.apple.com/documentation/uikit/uiresponder/touchesended(_:with:)
#app-main)
- UIKit
- UIResponder
- touchesEnded(_:with:)
Instance Method
touchesEnded(_:with:)
Tells the responder when one or more fingers are raised from a view or window.
tvOS
@MainActor func touchesEnded(
with event: UIEvent? )
Parameters
touches
A set of UITouch instances that represent the touches for the ending phase of the event represented by event. For touches in a view, this set contains only one touch by default. To receive multiple touches, you must set the view’s isMultipleTouchEnabled property to true.
event
The event to which the touches belong.
Mentioned in
Implementing a Multi-Touch app
Implementing a Discrete Gesture Recognizer
Implementing coalesced touch support in an app
Implementing a Continuous Gesture Recognizer
Discussion
UIKit calls this method when a finger or Apple Pencil is no longer touching the screen. Many UIKit classes override this method and use it to clean up state involved in the handling of the corresponding touch events. The default implementation of this method forwards the message up the responder chain. When creating your own subclasses, call super to forward any events that you don’t handle yourself, like in the following code.
super.touchesEnded(touches, with: event)
[super touchesEnded:touches withEvent:event];
If you override this method without calling super (a common use pattern), you must also override the other methods for handling touch events, even if your implementations do nothing.
See Also
Responding to touch events
Tells this object that one or more new touches occurred in a view or window.
Tells the responder when one or more touches associated with an event changed.
Tells the responder when a system event (such as a system alert) cancels a touch sequence.
Tells the responder that updated values were received for previously estimated properties or that an update is no longer expected.
https://developer.apple.com/documentation/uikit/uiresponder/touchescancelled(_:with:)
#app-main)
- UIKit
- UIResponder
- touchesCancelled(_:with:)
Instance Method
touchesCancelled(_:with:)
Tells the responder when a system event (such as a system alert) cancels a touch sequence.
tvOS
@MainActor func touchesCancelled(
with event: UIEvent? )
Parameters
touches
A set of UITouch instances that represent the touches for the ending phase of the event represented by event. For touches in a view, this set contains only one touch by default. To receive multiple touches, you must set the view’s isMultipleTouchEnabled property to true.
event
The event to which the touches belong.
Mentioned in
Implementing a Multi-Touch app
Implementing coalesced touch support in an app
About the Gesture Recognizer State Machine
Implementing a Discrete Gesture Recognizer
Implementing a Continuous Gesture Recognizer
Discussion
UIKit calls this method when it receives a system interruption requiring cancellation of the touch sequence. An interruption is anything that causes the application to become inactive or causes the view handling the touch events to be removed from its window. Your implementation of this method should clean up any state associated with handling the touch sequence. The default implementation of this method forwards the message up the responder chain. When creating your own subclasses, call super to forward any events that you don’t handle yourself, like in the following code.
super.touchesCancelled(touches, with: event)
[super touchesCancelled:touches withEvent:event];
If you override this method without calling super (a common use pattern), you must also override the other methods for handling touch events, if only as stub (empty) implementations.
See Also
Responding to touch events
Tells this object that one or more new touches occurred in a view or window.
Tells the responder when one or more touches associated with an event changed.
Tells the responder when one or more fingers are raised from a view or window.
Tells the responder that updated values were received for previously estimated properties or that an update is no longer expected.
https://developer.apple.com/documentation/uikit/uiview/addconstraint(_:)
#app-main)
- UIKit
- UIView
- addConstraint(_:)
Instance Method
addConstraint(_:)
Adds a constraint on the layout of the receiving view or its subviews.
tvOS
@MainActor func addConstraint(_ constraint: NSLayoutConstraint)
Parameters
constraint
The constraint to be added to the view. The constraint may only reference the view itself or its subviews.
Discussion
The constraint must involve only views that are within scope of the receiving view. Specifically, any views involved must be either the receiving view itself, or a subview of the receiving view. Constraints that are added to a view are said to be held by that view. The coordinate system used when evaluating the constraint is the coordinate system of the view that holds the constraint.
When developing for iOS 8.0 or later, set the constraint’s isActive property to true instead of calling the addConstraint(_:) method directly. The isActive property automatically adds and removes the constraint from the correct view.
See Also
Managing the view’s constraints
var constraints: [NSLayoutConstraint]
The constraints held by the view.
func addConstraints([NSLayoutConstraint])
Adds multiple constraints on the layout of the receiving view or its subviews.
func removeConstraint(NSLayoutConstraint)
Removes the specified constraint from the view.
func removeConstraints([NSLayoutConstraint])
Removes the specified constraints from the view.
https://developer.apple.com/documentation/uikit/uiview/autoresizingmask-swift.property
- UIKit
- UIView
- autoresizingMask
Instance Property
autoresizingMask
An integer bit mask that determines how the receiver resizes itself when its superview’s bounds change.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor var autoresizingMask: UIView.AutoresizingMask { get set }
Discussion
When a view’s bounds change, that view automatically resizes its subviews according to each subview’s autoresizing mask. You specify the value of this mask by combining the constants described in UIView.AutoresizingMask using the C bitwise OR operator. Combining these constants lets you specify which dimensions of the view should grow or shrink relative to the superview. The default value of this property is UIViewAutoresizingNone, which indicates that the view should not be resized at all.
When more than one option along the same axis is set, the default behavior is to distribute the size difference proportionally among the flexible portions. The larger the flexible portion, relative to the other flexible portions, the more it is likely to grow. For example, suppose this property includes the flexibleWidth and flexibleRightMargin constants but does not include the flexibleLeftMargin constant, thus indicating that the width of the view’s left margin is fixed but that the view’s width and right margin may change. Thus, the view appears anchored to the left side of its superview while both the view width and the gap to the right of the view increase.
If the autoresizing behaviors do not offer the precise layout that you need for your views, you can use a custom container view and override its layoutSubviews() method to position your subviews more precisely.
See Also
Configuring the resizing behavior
var contentMode: UIView.ContentMode
A flag used to determine how a view lays out its content when its bounds change.
enum ContentMode
Options to specify how a view adjusts its content when its size changes.
Asks the view to calculate and return the size that best fits the specified size.
func sizeToFit()
Resizes and moves the receiver view so it just encloses its subviews.
var autoresizesSubviews: Bool
A Boolean value that determines whether the receiver automatically resizes its subviews when its bounds change.
https://developer.apple.com/documentation/uikit/uiview/contentmode-swift.property
- UIKit
- UIView
- contentMode
Instance Property
contentMode
A flag used to determine how a view lays out its content when its bounds change.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor var contentMode: UIView.ContentMode { get set }
Discussion
The content mode specifies how the cached bitmap of the view’s layer is adjusted when the view’s bounds change. This property is often used to implement resizable controls. Instead of redrawing the contents of the view every time, you can use this property to specify that you want to scale the contents (either with or without distortion) or pin them to a particular spot on the view.
For a list of values you can assign to this property, see UIView.ContentMode. The default value of this property is UIView.ContentMode.scaleToFill.
See Also
Configuring the resizing behavior
enum ContentMode
Options to specify how a view adjusts its content when its size changes.
Asks the view to calculate and return the size that best fits the specified size.
func sizeToFit()
Resizes and moves the receiver view so it just encloses its subviews.
var autoresizesSubviews: Bool
A Boolean value that determines whether the receiver automatically resizes its subviews when its bounds change.
var autoresizingMask: UIView.AutoresizingMask
An integer bit mask that determines how the receiver resizes itself when its superview’s bounds change.
https://developer.apple.com/documentation/uikit/uiview/ishidden
- UIKit
- UIView
- isHidden
Instance Property
isHidden
A Boolean value that determines whether the view is hidden.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor var isHidden: Bool { get set }
Discussion
Setting the value of this property to true hides the receiver and setting it to false shows the receiver. The default value is false.
A hidden view disappears from its window and does not receive input events. It remains in its superview’s list of subviews, however, and participates in autoresizing as usual. Hiding a view with subviews has the effect of hiding those subviews and any view descendants they might have. This effect is implicit and does not alter the hidden state of the receiver’s descendants.
Hiding the view that is the window’s current first responder causes the view’s next valid key view to become the new first responder.
The value of this property reflects the state of the receiver only and does not account for the state of the receiver’s ancestors in the view hierarchy. Thus this property can be false but the receiver may still be hidden if an ancestor is hidden.
See Also
Configuring a view’s visual appearance
var backgroundColor: UIColor?
The view’s background color.
var alpha: CGFloat
The view’s alpha value.
var isOpaque: Bool
A Boolean value that determines whether the view is opaque.
var tintColor: UIColor!
The first nondefault tint color value in the view’s hierarchy, ascending from and starting with the view itself.
var tintAdjustmentMode: UIView.TintAdjustmentMode
The first non-default tint adjustment mode value in the view’s hierarchy, ascending from and starting with the view itself.
var clipsToBounds: Bool
A Boolean value that determines whether subviews are confined to the bounds of the view.
var clearsContextBeforeDrawing: Bool
A Boolean value that determines whether the view’s bounds should be automatically cleared before drawing.
var mask: UIView?
An optional view whose alpha channel is used to mask a view’s content.
class var layerClass: AnyClass
Returns the class used to create the layer for instances of this class.
var layer: CALayer
The view’s Core Animation layer to use for rendering.
https://developer.apple.com/documentation/uikit/uiview/init(coder:)
#app-main)
- UIKit
- UIView
- init(coder:)
Initializer
init(coder:)
Creates a view from data in an unarchiver.
tvOS
@MainActor init?(coder: NSCoder)
See Also
Creating a view object
init(frame: CGRect)
Creates a view with the specified frame rectangle.
https://developer.apple.com/documentation/uikit/uiview/isopaque
https://developer.apple.com/documentation/uikit/uiview/tintcolor
- UIKit
- UIView
- tintColor
Instance Property
tintColor
The first nondefault tint color value in the view’s hierarchy, ascending from and starting with the view itself.
tvOS
@MainActor var tintColor: UIColor! { get set }
Discussion
If the system cannot find a nondefault color in the hierarchy, this property’s value is a system-defined color instead.
If the view’s tintAdjustmentMode property’s value is UIView.TintAdjustmentMode.dimmed, then the tintColor property value is automatically dimmed.
To refresh subview rendering when this property changes, override the tintColorDidChange() method.
Colors that are pattern colors (as described in UIColor) are not supported.
See Also
Related Documentation
func tintColorDidChange()
Called by the system when the tint color property changes.
Configuring a view’s visual appearance
var backgroundColor: UIColor?
The view’s background color.
var isHidden: Bool
A Boolean value that determines whether the view is hidden.
var alpha: CGFloat
The view’s alpha value.
var isOpaque: Bool
A Boolean value that determines whether the view is opaque.
var tintAdjustmentMode: UIView.TintAdjustmentMode
The first non-default tint adjustment mode value in the view’s hierarchy, ascending from and starting with the view itself.
var clipsToBounds: Bool
A Boolean value that determines whether subviews are confined to the bounds of the view.
var clearsContextBeforeDrawing: Bool
A Boolean value that determines whether the view’s bounds should be automatically cleared before drawing.
var mask: UIView?
An optional view whose alpha channel is used to mask a view’s content.
class var layerClass: AnyClass
Returns the class used to create the layer for instances of this class.
var layer: CALayer
The view’s Core Animation layer to use for rendering.
https://developer.apple.com/documentation/uikit/uiview/tintadjustmentmode-swift.property
- UIKit
- UIView
- tintAdjustmentMode
Instance Property
tintAdjustmentMode
The first non-default tint adjustment mode value in the view’s hierarchy, ascending from and starting with the view itself.
tvOS
@MainActor var tintAdjustmentMode: UIView.TintAdjustmentMode { get set }
Discussion
When this property’s value is UIView.TintAdjustmentMode.dimmed, the value of the tintColor property is modified to provide a dimmed appearance.
If the system cannot find a non-default value in the subview hierarchy when you query this property, the value is UIView.TintAdjustmentMode.normal.
When this property’s value changes (either by the view’s value changing or by one of its superview’s values changing), the system calls the tintColorDidChange() method to allow the view to refresh its rendering.
See Also
Configuring a view’s visual appearance
var backgroundColor: UIColor?
The view’s background color.
var isHidden: Bool
A Boolean value that determines whether the view is hidden.
var alpha: CGFloat
The view’s alpha value.
var isOpaque: Bool
A Boolean value that determines whether the view is opaque.
var tintColor: UIColor!
The first nondefault tint color value in the view’s hierarchy, ascending from and starting with the view itself.
var clipsToBounds: Bool
A Boolean value that determines whether subviews are confined to the bounds of the view.
var clearsContextBeforeDrawing: Bool
A Boolean value that determines whether the view’s bounds should be automatically cleared before drawing.
var mask: UIView?
An optional view whose alpha channel is used to mask a view’s content.
class var layerClass: AnyClass
Returns the class used to create the layer for instances of this class.
var layer: CALayer
The view’s Core Animation layer to use for rendering.
https://developer.apple.com/documentation/uikit/uiview/clearscontextbeforedrawing
- UIKit
- UIView
- clearsContextBeforeDrawing
Instance Property
clearsContextBeforeDrawing
A Boolean value that determines whether the view’s bounds should be automatically cleared before drawing.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor var clearsContextBeforeDrawing: Bool { get set }
Discussion
When set to true, the drawing buffer is automatically cleared to transparent black before the draw(_:) method is called. This behavior ensures that there are no visual artifacts left over when the view’s contents are redrawn. If the view’s isOpaque property is also set to true, the backgroundColor property of the view must not be nil or drawing errors may occur. The default value of this property is true.
If you set the value of this property to false, you are responsible for ensuring the contents of the view are drawn properly in your draw(_:) method. If your drawing code is already heavily optimized, setting this property is false can improve performance, especially during scrolling when only a portion of the view might need to be redrawn.
See Also
Configuring a view’s visual appearance
var backgroundColor: UIColor?
The view’s background color.
var isHidden: Bool
A Boolean value that determines whether the view is hidden.
var alpha: CGFloat
The view’s alpha value.
var isOpaque: Bool
A Boolean value that determines whether the view is opaque.
var tintColor: UIColor!
The first nondefault tint color value in the view’s hierarchy, ascending from and starting with the view itself.
var tintAdjustmentMode: UIView.TintAdjustmentMode
The first non-default tint adjustment mode value in the view’s hierarchy, ascending from and starting with the view itself.
var clipsToBounds: Bool
A Boolean value that determines whether subviews are confined to the bounds of the view.
var mask: UIView?
An optional view whose alpha channel is used to mask a view’s content.
class var layerClass: AnyClass
Returns the class used to create the layer for instances of this class.
var layer: CALayer
The view’s Core Animation layer to use for rendering.
https://developer.apple.com/documentation/uikit/uiview/mask
- UIKit
- UIView
- mask
Instance Property
mask
An optional view whose alpha channel is used to mask a view’s content.
tvOS
@MainActor var mask: UIView? { get set }
Discussion
The view’s alpha channel determines how much of the view’s content and background shows through. Fully or partially opaque pixels allow the underlying content to show through but fully transparent pixels block that content.
See Also
Configuring a view’s visual appearance
var backgroundColor: UIColor?
The view’s background color.
var isHidden: Bool
A Boolean value that determines whether the view is hidden.
var alpha: CGFloat
The view’s alpha value.
var isOpaque: Bool
A Boolean value that determines whether the view is opaque.
var tintColor: UIColor!
The first nondefault tint color value in the view’s hierarchy, ascending from and starting with the view itself.
var tintAdjustmentMode: UIView.TintAdjustmentMode
The first non-default tint adjustment mode value in the view’s hierarchy, ascending from and starting with the view itself.
var clipsToBounds: Bool
A Boolean value that determines whether subviews are confined to the bounds of the view.
var clearsContextBeforeDrawing: Bool
A Boolean value that determines whether the view’s bounds should be automatically cleared before drawing.
class var layerClass: AnyClass
Returns the class used to create the layer for instances of this class.
var layer: CALayer
The view’s Core Animation layer to use for rendering.
https://developer.apple.com/documentation/uikit/uiview/layer
- UIKit
- UIView
- layer
Instance Property
layer
The view’s Core Animation layer to use for rendering.
tvOS
@MainActor var layer: CALayer { get }
Discussion
This property is never nil. The value of the layerClass property determines the actual class of the layer object. The view is the layer’s delegate.
See Also
Configuring a view’s visual appearance
var backgroundColor: UIColor?
The view’s background color.
var isHidden: Bool
A Boolean value that determines whether the view is hidden.
var alpha: CGFloat
The view’s alpha value.
var isOpaque: Bool
A Boolean value that determines whether the view is opaque.
var tintColor: UIColor!
The first nondefault tint color value in the view’s hierarchy, ascending from and starting with the view itself.
var tintAdjustmentMode: UIView.TintAdjustmentMode
The first non-default tint adjustment mode value in the view’s hierarchy, ascending from and starting with the view itself.
var clipsToBounds: Bool
A Boolean value that determines whether subviews are confined to the bounds of the view.
var clearsContextBeforeDrawing: Bool
A Boolean value that determines whether the view’s bounds should be automatically cleared before drawing.
var mask: UIView?
An optional view whose alpha channel is used to mask a view’s content.
class var layerClass: AnyClass
Returns the class used to create the layer for instances of this class.
https://developer.apple.com/documentation/uikit/uiview/isuserinteractionenabled
- UIKit
- UIView
- isUserInteractionEnabled
Instance Property
isUserInteractionEnabled
A Boolean value that determines whether user events are ignored and removed from the event queue.
tvOS
@MainActor var isUserInteractionEnabled: Bool { get set }
Mentioned in
Handling tap gestures
Handling pan gestures
Handling rotation gestures
Handling long-press gestures
Handling swipe gestures
Discussion
When set to false, touch, press, keyboard, and focus events intended for the view are ignored and removed from the event queue. When set to true, events are delivered to the view normally. The default value of this property is true.
During an animation, user interactions are temporarily disabled for all views involved in the animation, regardless of the value in this property. You can disable this behavior by specifying the allowUserInteraction option when configuring the animation.
See Also
Configuring the event-related behavior
var isMultipleTouchEnabled: Bool
A Boolean value that indicates whether the view receives more than one touch at a time.
var isExclusiveTouch: Bool
A Boolean value that indicates whether the receiver handles touch events exclusively.
https://developer.apple.com/documentation/uikit/uiview/ismultipletouchenabled
- UIKit
- UIView
- isMultipleTouchEnabled
Instance Property
isMultipleTouchEnabled
A Boolean value that indicates whether the view receives more than one touch at a time.
iOSiPadOSMac CatalystvisionOS
@MainActor var isMultipleTouchEnabled: Bool { get set }
Discussion
When set to true, the view receives all touches associated with a multi-touch sequence and starting within the view’s bounds. When set to false, the view receives only the first touch event in a multi-touch sequence that start within the view’s bounds. The default value of this property is false.
Other views in the same window can still receive touch events when this property is false. If you want this view to handle multi-touch events exclusively, set the values of both this property and the isExclusiveTouch property to true. This property does not prevent a view from being asked to handle multiple touches. For example, two subviews may both forward their touches to a common parent, such as a window or the root view of a view controller. This property determines how many touches initially targeting the view are delivered to that view.
See Also
Configuring the event-related behavior
var isUserInteractionEnabled: Bool
A Boolean value that determines whether user events are ignored and removed from the event queue.
var isExclusiveTouch: Bool
A Boolean value that indicates whether the receiver handles touch events exclusively.
https://developer.apple.com/documentation/uikit/uiview/isexclusivetouch
- UIKit
- UIView
- isExclusiveTouch
Instance Property
isExclusiveTouch
A Boolean value that indicates whether the receiver handles touch events exclusively.
iOSiPadOSMac CatalystvisionOS
@MainActor var isExclusiveTouch: Bool { get set }
Discussion
Setting this property to true causes the receiver to block the delivery of touch events to other views in the same window. The default value of this property is false.
See Also
Configuring the event-related behavior
var isUserInteractionEnabled: Bool
A Boolean value that determines whether user events are ignored and removed from the event queue.
var isMultipleTouchEnabled: Bool
A Boolean value that indicates whether the view receives more than one touch at a time.
https://developer.apple.com/documentation/uikit/uiview/transform3d
- UIKit
- UIView
- transform3D
Instance Property
transform3D
The three-dimensional transform to apply to the view.
@MainActor var transform3D: CATransform3D { get set }
Discussion
The default value of this property is CATransform3DIdentity.
See Also
Configuring the bounds and frame rectangles
var frame: CGRect
The frame rectangle, which describes the view’s location and size in its superview’s coordinate system.
var bounds: CGRect
The bounds rectangle, which describes the view’s location and size in its own coordinate system.
var center: CGPoint
The center point of the view’s frame rectangle.
var transform: CGAffineTransform
Specifies the transform applied to the view, relative to the center of its bounds.
var anchorPoint: CGPoint
The anchor point of the view’s bounds rectangle.
https://developer.apple.com/documentation/uikit/uiview/anchorpoint
- UIKit
- UIView
- anchorPoint
Instance Property
anchorPoint
The anchor point of the view’s bounds rectangle.
@MainActor var anchorPoint: CGPoint { get set }
Discussion
You specify the value for this property using the unit coordinate space, where ( 0, 0) is the bottom-left corner of the view’s bounds rectangle, and ( 1, 1) is the top-right corner. The default value of this property is ( 0.5, 0.5), which represents the center of the view’s bounds rectangle.
All geometric manipulations to the view occur about the specified point. For example, applying a rotation transform to a view with the default anchor point causes the view to rotate around its center. Changing the anchor point to a different location causes the view to rotate around that new point.
See Also
Configuring the bounds and frame rectangles
var frame: CGRect
The frame rectangle, which describes the view’s location and size in its superview’s coordinate system.
var bounds: CGRect
The bounds rectangle, which describes the view’s location and size in its own coordinate system.
var center: CGPoint
The center point of the view’s frame rectangle.
var transform: CGAffineTransform
Specifies the transform applied to the view, relative to the center of its bounds.
var transform3D: CATransform3D
The three-dimensional transform to apply to the view.
https://developer.apple.com/documentation/uikit/uiview/superview
- UIKit
- UIView
- superview
Instance Property
superview
The receiver’s superview, or nil if it has none.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor var superview: UIView? { get }
See Also
Managing the view hierarchy
The receiver’s immediate subviews.
var window: UIWindow?
The receiver’s window object, or nil if it has none.
func addSubview(UIView)
Adds a view to the end of the receiver’s list of subviews.
func bringSubviewToFront(UIView)
Moves the specified subview so that it appears on top of its siblings.
func sendSubviewToBack(UIView)
Moves the specified subview so that it appears behind its siblings.
func removeFromSuperview()
Unlinks the view from its superview and its window, and removes it from the responder chain.
func insertSubview(UIView, at: Int)
Inserts a subview at the specified index.
func insertSubview(UIView, aboveSubview: UIView)
Inserts a view above another view in the view hierarchy.
func insertSubview(UIView, belowSubview: UIView)
Inserts a view below another view in the view hierarchy.
func exchangeSubview(at: Int, withSubviewAt: Int)
Exchanges the subviews at the specified indices.
Returns a Boolean value indicating whether the receiver is a subview of a given view or identical to that view.
https://developer.apple.com/documentation/uikit/uiview/window
https://developer.apple.com/documentation/uikit/uiview/bringsubviewtofront(_:)
https://developer.apple.com/documentation/uikit/uiview/sendsubviewtoback(_:)
#app-main)
- UIKit
- UIView
- sendSubviewToBack(_:)
Instance Method
sendSubviewToBack(_:)
Moves the specified subview so that it appears behind its siblings.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor func sendSubviewToBack(_ view: UIView)
Parameters
view
The subview to move to the back.
Discussion
This method moves the specified view to the beginning of the array of views in the subviews property.
See Also
Managing the view hierarchy
var superview: UIView?
The receiver’s superview, or nil if it has none.
The receiver’s immediate subviews.
var window: UIWindow?
The receiver’s window object, or nil if it has none.
func addSubview(UIView)
Adds a view to the end of the receiver’s list of subviews.
func bringSubviewToFront(UIView)
Moves the specified subview so that it appears on top of its siblings.
func removeFromSuperview()
Unlinks the view from its superview and its window, and removes it from the responder chain.
func insertSubview(UIView, at: Int)
Inserts a subview at the specified index.
func insertSubview(UIView, aboveSubview: UIView)
Inserts a view above another view in the view hierarchy.
func insertSubview(UIView, belowSubview: UIView)
Inserts a view below another view in the view hierarchy.
func exchangeSubview(at: Int, withSubviewAt: Int)
Exchanges the subviews at the specified indices.
Returns a Boolean value indicating whether the receiver is a subview of a given view or identical to that view.
https://developer.apple.com/documentation/uikit/uiview/removefromsuperview()
https://developer.apple.com/documentation/uikit/uiview/insertsubview(_:at:)
https://developer.apple.com/documentation/uikit/uiview/isdescendant(of:)
#app-main)
- UIKit
- UIView
- isDescendant(of:)
Instance Method
isDescendant(of:)
Returns a Boolean value indicating whether the receiver is a subview of a given view or identical to that view.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor
Parameters
view
The view to test against the receiver’s view hierarchy.
Return Value
true if the receiver is an immediate or distant subview of view or if view is the receiver itself; otherwise false.
See Also
Managing the view hierarchy
var superview: UIView?
The receiver’s superview, or nil if it has none.
The receiver’s immediate subviews.
var window: UIWindow?
The receiver’s window object, or nil if it has none.
func addSubview(UIView)
Adds a view to the end of the receiver’s list of subviews.
func bringSubviewToFront(UIView)
Moves the specified subview so that it appears on top of its siblings.
func sendSubviewToBack(UIView)
Moves the specified subview so that it appears behind its siblings.
func removeFromSuperview()
Unlinks the view from its superview and its window, and removes it from the responder chain.
func insertSubview(UIView, at: Int)
Inserts a subview at the specified index.
func insertSubview(UIView, aboveSubview: UIView)
Inserts a view above another view in the view hierarchy.
func insertSubview(UIView, belowSubview: UIView)
Inserts a view below another view in the view hierarchy.
func exchangeSubview(at: Int, withSubviewAt: Int)
Exchanges the subviews at the specified indices.
https://developer.apple.com/documentation/uikit/uiview/willmove(towindow:)
#app-main)
- UIKit
- UIView
- willMove(toWindow:)
Instance Method
willMove(toWindow:)
Tells the view that its window object is about to change.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor func willMove(toWindow newWindow: UIWindow?)
Parameters
newWindow
The window object that will be at the root of the receiver’s new view hierarchy. This parameter may be nil.
Discussion
The default implementation of this method does nothing. Subclasses can override it to perform additional actions whenever the window changes.
See Also
Observing view-related changes
func didAddSubview(UIView)
Tells the view that a subview was added.
func willRemoveSubview(UIView)
Tells the view that a subview is about to be removed.
func willMove(toSuperview: UIView?)
Tells the view that its superview is about to change to the specified superview.
func didMoveToSuperview()
Tells the view that its superview changed.
func didMoveToWindow()
Tells the view that its window object changed.
https://developer.apple.com/documentation/uikit/uiview/didmovetowindow()
https://developer.apple.com/documentation/uikit/uiview/updatetraitsifneeded()
#app-main)
- UIKit
- UIView
- updateTraitsIfNeeded()
Instance Method
updateTraitsIfNeeded()
@MainActor func updateTraitsIfNeeded()
https://developer.apple.com/documentation/uikit/uiview/traitoverrides-fd9z
- UIKit
- UIView
- traitOverrides
Instance Property
traitOverrides
Mac CatalystvisionOS
@MainActor @preconcurrency var traitOverrides: UITraitOverrides { get set }
See Also
Overriding trait values
struct UITraitOverrides
https://developer.apple.com/documentation/uikit/uitraitoverrides-swift.struct
- UIKit
- UITraitOverrides
Structure
UITraitOverrides
Mac CatalystvisionOS
struct UITraitOverrides
Topics
Instance Methods
func remove(UITrait)
Relationships
Conforms To
CopyableCustomDebugStringConvertibleCustomReflectableCustomStringConvertibleUIMutableTraits
See Also
Overriding trait values
var traitOverrides: UITraitOverrides
https://developer.apple.com/documentation/uikit/positioning-content-within-layout-margins
- UIKit
- View layout
- Positioning content within layout margins
Article
Positioning content within layout margins
Position views so that they aren’t crowded by other content.
Overview
Layout margins provide a visual buffer between a view’s content and any content outside of the view’s bounds. The layout margins consist of inset values for each edge (top, bottom, leading, and trailing) of the view. These inset values create a space between the edges of the view’s bounds rectangle and the content inside the view. The following image shows two views with different sets of layout margins. Apart from the empty space they add around your content, margins have no visible representation.
To set up constraints that respect the layout margins, enable the Constrain to margins option in Xcode, as shown in the following image. (If you don’t enable that option, Xcode creates your constraints relative to the view’s bounds rectangle.) If the superview’s margins change later, the positions of elements tied to those margins are updated accordingly.
Even if you aren’t using constraints to position your content, you can still manually position content relative to a view’s layout margins. The directionalLayoutMargins property of each view contains the edge inset values to use for the view’s margins. Take those margin values into account when computing the position of items in your view.
Change the default layout margins
UIKit provides default layout margins for each view, but you can change the default values to values that are more appropriate for your view. To change a view’s margin values, update the view’s directionalLayoutMargins property. (You can also use the Size inspector to set the value of that property at design time. In the Layout Margins section, choose the Language Directional option and enter the margin values for each of the view’s edges, as shown in the following image.)
For the root view of a view controller, UIKit enforces a set of minimum layout margins to ensure that content is displayed correctly. When the values in the directionalLayoutMargins property are less than the minimum values, UIKit uses the minimum values instead. You can get the minimum margin values from the systemMinimumLayoutMargins property of the view controller. To prevent UIKit from applying the minimum margins altogether, set the viewRespectsSystemMinimumLayoutMargins property of your view controller to false.
The view’s actual margins are computed using the view’s configuration and the value of its directionalLayoutMargins property. A view’s margins are affected by the settings of its insetsLayoutMarginsFromSafeArea and preservesSuperviewLayoutMargins properties, which can increase the default margin values to ensure appropriate spacing of your content.
See Also
Constraints
Positioning content relative to the safe area
Position views so that they aren’t obstructed by other content.
class NSLayoutConstraint
The relationship between two user interface objects that must be satisfied by the constraint-based layout system.
protocol UILayoutSupport
A set of methods that provide layout support and access to layout anchors.
https://developer.apple.com/documentation/uikit/uiview/directionallayoutmargins
- UIKit
- UIView
- directionalLayoutMargins
Instance Property
directionalLayoutMargins
The default spacing to use when laying out content in a view, taking into account the current language direction.
@MainActor var directionalLayoutMargins: NSDirectionalEdgeInsets { get set }
Mentioned in
Positioning content within layout margins
Discussion
Use this property to specify the desired amount of space (measured in points) between the edges of this view and its subviews. The leading and trailing margins are applied appropriately to the left or right margins based on the current layout direction. For example, the leading margin is applied to the right edge of the view in right-to-left layouts. For most views, the default layout margins are 8 points on each side. You can change these values as needed for your interface.
For the root view of a view controller, the default value of this property reflects the system minimum margins and safe area insets. For other subviews in your view hierarchy, the default layout margins are normally 8 points on each side, but the values may be greater if the view is not fully inside the safe area or if the preservesSuperviewLayoutMargins property is true.
Auto layout uses your margins as a cue for placing content. For example, if you specify a set of horizontal constraints using the format string “ |-[subview]-|”, the leading and trailing edges of the subview are inset from the edge of the superview by the corresponding layout margins. When the edge of your view is close to the edge of the superview and the preservesSuperviewLayoutMargins property is true, the actual layout margins may be increased to prevent content from overlapping the superview’s margins.
See Also
Configuring content margins
Position views so that they aren’t crowded by other content.
var layoutMargins: UIEdgeInsets
The default spacing to use when laying out content in the view.
var preservesSuperviewLayoutMargins: Bool
A Boolean value indicating whether the current view also respects the margins of its superview.
func layoutMarginsDidChange()
Notifies the view that the layout margins changed.
https://developer.apple.com/documentation/uikit/uiview/layoutmargins
- UIKit
- UIView
- layoutMargins
Instance Property
layoutMargins
The default spacing to use when laying out content in the view.
tvOS
@MainActor var layoutMargins: UIEdgeInsets { get set }
Discussion
In iOS 11 and later, use the directionalLayoutMargins property to specify layout margins instead of this property. The leading and trailing edge insets in the directionalLayoutMargins property are synchronized with the left and right insets in this property. For example, setting the leading directional edge inset to 20 points causes the left inset of this property to be set to 20 points on a system with a left-to-right language.
For the root view of a view controller, the default value of this property reflects the system minimum margins and safe area insets. For other subviews in your view hierarchy, the default layout margins are normally 8 points on each side, but the values may be greater if the view is not fully inside the safe area or if the preservesSuperviewLayoutMargins property is true.
This property specifies the desired amount of space (measured in points) between the edge of the view and any subviews. Auto layout uses your margins as a cue for placing content. For example, if you specify a set of horizontal constraints using the format string “ |-[subview]-|”, the left and right edges of the subview are inset from the edge of the superview by the corresponding layout margins. When the edge of your view is close to the edge of the superview and the preservesSuperviewLayoutMargins property is true, the actual layout margins may be increased to prevent content from overlapping the superview’s margins.
See Also
Configuring content margins
Positioning content within layout margins
Position views so that they aren’t crowded by other content.
var directionalLayoutMargins: NSDirectionalEdgeInsets
The default spacing to use when laying out content in a view, taking into account the current language direction.
var preservesSuperviewLayoutMargins: Bool
A Boolean value indicating whether the current view also respects the margins of its superview.
func layoutMarginsDidChange()
Notifies the view that the layout margins changed.
https://developer.apple.com/documentation/uikit/uiview/preservessuperviewlayoutmargins
- UIKit
- UIView
- preservesSuperviewLayoutMargins
Instance Property
preservesSuperviewLayoutMargins
A Boolean value indicating whether the current view also respects the margins of its superview.
tvOS
@MainActor var preservesSuperviewLayoutMargins: Bool { get set }
Mentioned in
Positioning content within layout margins
Discussion
When the value of this property is true, the superview’s margins are also considered when laying out content. This margin affects layouts where the distance between the edge of a view and its superview is smaller than the corresponding margin. For example, you might have a content view whose frame precisely matches the bounds of its superview. When any of the superview’s margins is inside the area represented by the content view and its own margins, UIKit adjusts the content view’s layout to respect the superview’s margins. The amount of the adjustment is the smallest amount needed to ensure that content is also inside the superview’s margins.
The default value of this property is false.
See Also
Configuring content margins
Position views so that they aren’t crowded by other content.
var directionalLayoutMargins: NSDirectionalEdgeInsets
The default spacing to use when laying out content in a view, taking into account the current language direction.
var layoutMargins: UIEdgeInsets
The default spacing to use when laying out content in the view.
func layoutMarginsDidChange()
Notifies the view that the layout margins changed.
https://developer.apple.com/documentation/uikit/uiview/layoutmarginsdidchange()
#app-main)
- UIKit
- UIView
- layoutMarginsDidChange()
Instance Method
layoutMarginsDidChange()
Notifies the view that the layout margins changed.
tvOS
@MainActor func layoutMarginsDidChange()
Discussion
The default implementation of this method does nothing. Subclasses can override this method and use it to respond when the value in the view’s layoutMargins property changes. For example, you might override this method if your view subclass handles layout manually or uses the layout margins during drawing. In both cases, you could use this method to initiate a drawing or layout update.
See Also
Configuring content margins
Positioning content within layout margins
Position views so that they aren’t crowded by other content.
var directionalLayoutMargins: NSDirectionalEdgeInsets
The default spacing to use when laying out content in a view, taking into account the current language direction.
var layoutMargins: UIEdgeInsets
The default spacing to use when laying out content in the view.
var preservesSuperviewLayoutMargins: Bool
A Boolean value indicating whether the current view also respects the margins of its superview.
https://developer.apple.com/documentation/uikit/positioning-content-relative-to-the-safe-area
https://developer.apple.com/documentation/uikit/uiview/safeareainsets
- UIKit
- UIView
- safeAreaInsets
Instance Property
safeAreaInsets
The insets that you use to determine the safe area for this view.
@MainActor var safeAreaInsets: UIEdgeInsets { get }
Mentioned in
Positioning content relative to the safe area
Discussion
The safe area of a view reflects the area not covered by navigation bars, tab bars, toolbars, and other ancestors that obscure a view controller’s view. (In tvOS, the safe area reflects the area not covered by the screen’s bezel.) You obtain the safe area for a view by applying the insets in this property to the view’s bounds rectangle. If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the edge insets in this property are 0.
For the view controller’s root view, the insets account for the status bar, other visible bars, and any additional insets that you specified using the additionalSafeAreaInsets property of your view controller. For other views in the view hierarchy, the insets reflect only the portion of the view that is covered. For example, if a view is entirely within the safe area of its superview, the edge insets in this property are 0.
You might use this property at runtime to adjust the position of your view’s content programmatically.
See Also
Related Documentation
var overscanCompensationInsets: UIEdgeInsets
The edge inset values needed to avoid clipping the rectangle.
Getting the safe area
Position views so that they aren’t obstructed by other content.
var safeAreaLayoutGuide: UILayoutGuide
The layout guide representing the portion of your view that is unobscured by bars and other content.
func safeAreaInsetsDidChange()
Called when the safe area of the view changes.
var insetsLayoutMarginsFromSafeArea: Bool
A Boolean value indicating whether the view’s layout margins are updated automatically to reflect the safe area.
https://developer.apple.com/documentation/uikit/uiview/safearealayoutguide
- UIKit
- UIView
- safeAreaLayoutGuide
Instance Property
safeAreaLayoutGuide
The layout guide representing the portion of your view that is unobscured by bars and other content.
@MainActor var safeAreaLayoutGuide: UILayoutGuide { get }
Mentioned in
Positioning content relative to the safe area
Discussion
When the view is visible onscreen, this guide reflects the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor views. (In tvOS, the safe area reflects the area not covered the screen’s bezel.) If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the layout guide edges are equal to the edges of the view.
For the view controller’s root view, the layout guide accommodates the status bar, other visible bars, and any additional insets that you specified using the additionalSafeAreaInsets property of your view controller. For other views in the view hierarchy, the layout guide reflects only the portion of the view that is covered by other content. For example, if a view is entirely within the safe area of its superview, the layout guide edges are equal to the edges of the view.
See Also
Getting the safe area
Position views so that they aren’t obstructed by other content.
var safeAreaInsets: UIEdgeInsets
The insets that you use to determine the safe area for this view.
func safeAreaInsetsDidChange()
Called when the safe area of the view changes.
var insetsLayoutMarginsFromSafeArea: Bool
A Boolean value indicating whether the view’s layout margins are updated automatically to reflect the safe area.
https://developer.apple.com/documentation/uikit/uiview/safeareainsetsdidchange()
#app-main)
- UIKit
- UIView
- safeAreaInsetsDidChange()
Instance Method
safeAreaInsetsDidChange()
Called when the safe area of the view changes.
@MainActor func safeAreaInsetsDidChange()
See Also
Getting the safe area
Positioning content relative to the safe area
Position views so that they aren’t obstructed by other content.
var safeAreaInsets: UIEdgeInsets
The insets that you use to determine the safe area for this view.
var safeAreaLayoutGuide: UILayoutGuide
The layout guide representing the portion of your view that is unobscured by bars and other content.
var insetsLayoutMarginsFromSafeArea: Bool
A Boolean value indicating whether the view’s layout margins are updated automatically to reflect the safe area.
https://developer.apple.com/documentation/uikit/uiview/insetslayoutmarginsfromsafearea
- UIKit
- UIView
- insetsLayoutMarginsFromSafeArea
Instance Property
insetsLayoutMarginsFromSafeArea
A Boolean value indicating whether the view’s layout margins are updated automatically to reflect the safe area.
@MainActor var insetsLayoutMarginsFromSafeArea: Bool { get set }
Mentioned in
Positioning content within layout margins
Discussion
When the value of this property is true, any margins that are outside the safe area are automatically modified to fall within the safe area boundary. The default value of this property is true. Changing the value to false allows your margins to remain at their original locations, even when they are outside the safe area.
See Also
Getting the safe area
Positioning content relative to the safe area
Position views so that they aren’t obstructed by other content.
var safeAreaInsets: UIEdgeInsets
The insets that you use to determine the safe area for this view.
var safeAreaLayoutGuide: UILayoutGuide
The layout guide representing the portion of your view that is unobscured by bars and other content.
func safeAreaInsetsDidChange()
Called when the safe area of the view changes.
https://developer.apple.com/documentation/uikit/uiview/removeconstraint(_:)
#app-main)
- UIKit
- UIView
- removeConstraint(_:)
Instance Method
removeConstraint(_:)
Removes the specified constraint from the view.
tvOS
@MainActor func removeConstraint(_ constraint: NSLayoutConstraint)
Parameters
constraint
The constraint to remove. Removing a constraint not held by the view has no effect.
Discussion
When developing for iOS 8.0 or later, set the constraint’s isActive property to false instead of calling the removeConstraint(_:) method directly. The isActive property automatically adds and removes the constraint from the correct view.
See Also
Managing the view’s constraints
var constraints: [NSLayoutConstraint]
The constraints held by the view.
func addConstraint(NSLayoutConstraint)
Adds a constraint on the layout of the receiving view or its subviews.
func addConstraints([NSLayoutConstraint])
Adds multiple constraints on the layout of the receiving view or its subviews.
func removeConstraints([NSLayoutConstraint])
Removes the specified constraints from the view.
https://developer.apple.com/documentation/uikit/uiview/bottomanchor
- UIKit
- UIView
- bottomAnchor
Instance Property
bottomAnchor
A layout anchor representing the bottom edge of the view’s frame.
@MainActor var bottomAnchor: NSLayoutYAxisAnchor { get }
Discussion
Use this anchor to create constraints with the view’s bottom edge. You can combine this anchor only with other NSLayoutYAxisAnchor anchors. For more information, see NSLayoutAnchor.
See Also
Creating constraints using layout anchors
var centerXAnchor: NSLayoutXAxisAnchor
A layout anchor representing the horizontal center of the view’s frame.
var centerYAnchor: NSLayoutYAxisAnchor
A layout anchor representing the vertical center of the view’s frame.
var firstBaselineAnchor: NSLayoutYAxisAnchor
A layout anchor representing the baseline for the topmost line of text in the view.
var heightAnchor: NSLayoutDimension
A layout anchor representing the height of the view’s frame.
var lastBaselineAnchor: NSLayoutYAxisAnchor
A layout anchor representing the baseline for the bottommost line of text in the view.
var leadingAnchor: NSLayoutXAxisAnchor
A layout anchor representing the leading edge of the view’s frame.
var leftAnchor: NSLayoutXAxisAnchor
A layout anchor representing the left edge of the view’s frame.
var rightAnchor: NSLayoutXAxisAnchor
A layout anchor representing the right edge of the view’s frame.
var topAnchor: NSLayoutYAxisAnchor
A layout anchor representing the top edge of the view’s frame.
var trailingAnchor: NSLayoutXAxisAnchor
A layout anchor representing the trailing edge of the view’s frame.
var widthAnchor: NSLayoutDimension
A layout anchor representing the width of the view’s frame.
https://developer.apple.com/documentation/uikit/uiview/centerxanchor
- UIKit
- UIView
- centerXAnchor
Instance Property
centerXAnchor
A layout anchor representing the horizontal center of the view’s frame.
@MainActor var centerXAnchor: NSLayoutXAxisAnchor { get }
Discussion
Use this anchor to create constraints with the view’s horizontal center. You can combine this anchor only with other NSLayoutXAxisAnchor anchors. For more information, see NSLayoutAnchor.
See Also
Creating constraints using layout anchors
var bottomAnchor: NSLayoutYAxisAnchor
A layout anchor representing the bottom edge of the view’s frame.
var centerYAnchor: NSLayoutYAxisAnchor
A layout anchor representing the vertical center of the view’s frame.
var firstBaselineAnchor: NSLayoutYAxisAnchor
A layout anchor representing the baseline for the topmost line of text in the view.
var heightAnchor: NSLayoutDimension
A layout anchor representing the height of the view’s frame.
var lastBaselineAnchor: NSLayoutYAxisAnchor
A layout anchor representing the baseline for the bottommost line of text in the view.
var leadingAnchor: NSLayoutXAxisAnchor
A layout anchor representing the leading edge of the view’s frame.
var leftAnchor: NSLayoutXAxisAnchor
A layout anchor representing the left edge of the view’s frame.
var rightAnchor: NSLayoutXAxisAnchor
A layout anchor representing the right edge of the view’s frame.
var topAnchor: NSLayoutYAxisAnchor
A layout anchor representing the top edge of the view’s frame.
var trailingAnchor: NSLayoutXAxisAnchor
A layout anchor representing the trailing edge of the view’s frame.
var widthAnchor: NSLayoutDimension
A layout anchor representing the width of the view’s frame.
https://developer.apple.com/documentation/uikit/uiview/centeryanchor
https://developer.apple.com/documentation/uikit/uiview/firstbaselineanchor
- UIKit
- UIView
- firstBaselineAnchor
Instance Property
firstBaselineAnchor
A layout anchor representing the baseline for the topmost line of text in the view.
@MainActor var firstBaselineAnchor: NSLayoutYAxisAnchor { get }
Mentioned in
Configuring and displaying symbol images in your UI
Discussion
For views with multiple lines of text, this anchor represents the baseline of the top row of text. Use this anchor to create constraints with this baseline. You can combine this anchor only with other NSLayoutYAxisAnchor anchors. For more information, see NSLayoutAnchor.
See Also
Creating constraints using layout anchors
var bottomAnchor: NSLayoutYAxisAnchor
A layout anchor representing the bottom edge of the view’s frame.
var centerXAnchor: NSLayoutXAxisAnchor
A layout anchor representing the horizontal center of the view’s frame.
var centerYAnchor: NSLayoutYAxisAnchor
A layout anchor representing the vertical center of the view’s frame.
var heightAnchor: NSLayoutDimension
A layout anchor representing the height of the view’s frame.
var lastBaselineAnchor: NSLayoutYAxisAnchor
A layout anchor representing the baseline for the bottommost line of text in the view.
var leadingAnchor: NSLayoutXAxisAnchor
A layout anchor representing the leading edge of the view’s frame.
var leftAnchor: NSLayoutXAxisAnchor
A layout anchor representing the left edge of the view’s frame.
var rightAnchor: NSLayoutXAxisAnchor
A layout anchor representing the right edge of the view’s frame.
var topAnchor: NSLayoutYAxisAnchor
A layout anchor representing the top edge of the view’s frame.
var trailingAnchor: NSLayoutXAxisAnchor
A layout anchor representing the trailing edge of the view’s frame.
var widthAnchor: NSLayoutDimension
A layout anchor representing the width of the view’s frame.
https://developer.apple.com/documentation/uikit/uiview/heightanchor
- UIKit
- UIView
- heightAnchor
Instance Property
heightAnchor
A layout anchor representing the height of the view’s frame.
@MainActor var heightAnchor: NSLayoutDimension { get }
Discussion
Use this anchor to create constraints with the view’s height. You can combine this anchor only with other NSLayoutDimension anchors. For more information, see NSLayoutAnchor.
See Also
Creating constraints using layout anchors
var bottomAnchor: NSLayoutYAxisAnchor
A layout anchor representing the bottom edge of the view’s frame.
var centerXAnchor: NSLayoutXAxisAnchor
A layout anchor representing the horizontal center of the view’s frame.
var centerYAnchor: NSLayoutYAxisAnchor
A layout anchor representing the vertical center of the view’s frame.
var firstBaselineAnchor: NSLayoutYAxisAnchor
A layout anchor representing the baseline for the topmost line of text in the view.
var lastBaselineAnchor: NSLayoutYAxisAnchor
A layout anchor representing the baseline for the bottommost line of text in the view.
var leadingAnchor: NSLayoutXAxisAnchor
A layout anchor representing the leading edge of the view’s frame.
var leftAnchor: NSLayoutXAxisAnchor
A layout anchor representing the left edge of the view’s frame.
var rightAnchor: NSLayoutXAxisAnchor
A layout anchor representing the right edge of the view’s frame.
var topAnchor: NSLayoutYAxisAnchor
A layout anchor representing the top edge of the view’s frame.
var trailingAnchor: NSLayoutXAxisAnchor
A layout anchor representing the trailing edge of the view’s frame.
var widthAnchor: NSLayoutDimension
A layout anchor representing the width of the view’s frame.
https://developer.apple.com/documentation/uikit/uiview/lastbaselineanchor
- UIKit
- UIView
- lastBaselineAnchor
Instance Property
lastBaselineAnchor
A layout anchor representing the baseline for the bottommost line of text in the view.
@MainActor var lastBaselineAnchor: NSLayoutYAxisAnchor { get }
Discussion
For views with multiple lines of text, this anchor represents the baseline of the bottom row of text. Use this anchor to create constraints with this baseline. You can combine this anchor only with other NSLayoutYAxisAnchor anchors. For more information, see NSLayoutAnchor.
See Also
Creating constraints using layout anchors
var bottomAnchor: NSLayoutYAxisAnchor
A layout anchor representing the bottom edge of the view’s frame.
var centerXAnchor: NSLayoutXAxisAnchor
A layout anchor representing the horizontal center of the view’s frame.
var centerYAnchor: NSLayoutYAxisAnchor
A layout anchor representing the vertical center of the view’s frame.
var firstBaselineAnchor: NSLayoutYAxisAnchor
A layout anchor representing the baseline for the topmost line of text in the view.
var heightAnchor: NSLayoutDimension
A layout anchor representing the height of the view’s frame.
var leadingAnchor: NSLayoutXAxisAnchor
A layout anchor representing the leading edge of the view’s frame.
var leftAnchor: NSLayoutXAxisAnchor
A layout anchor representing the left edge of the view’s frame.
var rightAnchor: NSLayoutXAxisAnchor
A layout anchor representing the right edge of the view’s frame.
var topAnchor: NSLayoutYAxisAnchor
A layout anchor representing the top edge of the view’s frame.
var trailingAnchor: NSLayoutXAxisAnchor
A layout anchor representing the trailing edge of the view’s frame.
var widthAnchor: NSLayoutDimension
A layout anchor representing the width of the view’s frame.
https://developer.apple.com/documentation/uikit/uiview/leadinganchor
https://developer.apple.com/documentation/uikit/uiview/leftanchor
https://developer.apple.com/documentation/uikit/uiview/rightanchor
- UIKit
- UIView
- rightAnchor
Instance Property
rightAnchor
A layout anchor representing the right edge of the view’s frame.
@MainActor var rightAnchor: NSLayoutXAxisAnchor { get }
Discussion
Use this anchor to create constraints with the view’s right edge. You can combine this anchor only with a subset of the NSLayoutXAxisAnchor anchors. You can combine a UIView with another rightAnchor, a leftAnchor, or a centerXAnchor. For more information, see NSLayoutAnchor.
See Also
Creating constraints using layout anchors
var bottomAnchor: NSLayoutYAxisAnchor
A layout anchor representing the bottom edge of the view’s frame.
var centerXAnchor: NSLayoutXAxisAnchor
A layout anchor representing the horizontal center of the view’s frame.
var centerYAnchor: NSLayoutYAxisAnchor
A layout anchor representing the vertical center of the view’s frame.
var firstBaselineAnchor: NSLayoutYAxisAnchor
A layout anchor representing the baseline for the topmost line of text in the view.
var heightAnchor: NSLayoutDimension
A layout anchor representing the height of the view’s frame.
var lastBaselineAnchor: NSLayoutYAxisAnchor
A layout anchor representing the baseline for the bottommost line of text in the view.
var leadingAnchor: NSLayoutXAxisAnchor
A layout anchor representing the leading edge of the view’s frame.
var leftAnchor: NSLayoutXAxisAnchor
A layout anchor representing the left edge of the view’s frame.
var topAnchor: NSLayoutYAxisAnchor
A layout anchor representing the top edge of the view’s frame.
var trailingAnchor: NSLayoutXAxisAnchor
A layout anchor representing the trailing edge of the view’s frame.
var widthAnchor: NSLayoutDimension
A layout anchor representing the width of the view’s frame.
https://developer.apple.com/documentation/uikit/uiview/topanchor
https://developer.apple.com/documentation/uikit/uiview/trailinganchor
- UIKit
- UIView
- trailingAnchor
Instance Property
trailingAnchor
A layout anchor representing the trailing edge of the view’s frame.
@MainActor var trailingAnchor: NSLayoutXAxisAnchor { get }
Discussion
Use this anchor to create constraints with the view’s trailing edge. You can combine this anchor only with a subset of the NSLayoutXAxisAnchor anchors. You can combine a UIView with another trailingAnchor, a leadingAnchor, or a centerXAnchor. For more information, see NSLayoutAnchor.
See Also
Creating constraints using layout anchors
var bottomAnchor: NSLayoutYAxisAnchor
A layout anchor representing the bottom edge of the view’s frame.
var centerXAnchor: NSLayoutXAxisAnchor
A layout anchor representing the horizontal center of the view’s frame.
var centerYAnchor: NSLayoutYAxisAnchor
A layout anchor representing the vertical center of the view’s frame.
var firstBaselineAnchor: NSLayoutYAxisAnchor
A layout anchor representing the baseline for the topmost line of text in the view.
var heightAnchor: NSLayoutDimension
A layout anchor representing the height of the view’s frame.
var lastBaselineAnchor: NSLayoutYAxisAnchor
A layout anchor representing the baseline for the bottommost line of text in the view.
var leadingAnchor: NSLayoutXAxisAnchor
A layout anchor representing the leading edge of the view’s frame.
var leftAnchor: NSLayoutXAxisAnchor
A layout anchor representing the left edge of the view’s frame.
var rightAnchor: NSLayoutXAxisAnchor
A layout anchor representing the right edge of the view’s frame.
var topAnchor: NSLayoutYAxisAnchor
A layout anchor representing the top edge of the view’s frame.
var widthAnchor: NSLayoutDimension
A layout anchor representing the width of the view’s frame.
https://developer.apple.com/documentation/uikit/uiview/widthanchor
https://developer.apple.com/documentation/uikit/uiview/addlayoutguide(_:)
#app-main)
- UIKit
- UIView
- addLayoutGuide(_:)
Instance Method
addLayoutGuide(_:)
Adds the specified layout guide to the view.
@MainActor func addLayoutGuide(_ layoutGuide: UILayoutGuide)
Parameters
layoutGuide
The layout guide to be added.
Discussion
This method adds the specified layout guide to the end of the view’s layoutGuides array. It also assigns the view to the guide’s owningView property. Each guide can have only one owning view.
After the guide has been added to a view, it can participate in Auto Layout constraints with that view’s hierarchy.
See Also
Working with layout guides
var layoutGuides: [UILayoutGuide]
The array of layout guide objects owned by this view.
var layoutMarginsGuide: UILayoutGuide
A layout guide representing the view’s margins.
var readableContentGuide: UILayoutGuide
A layout guide representing an area with a readable width within the view.
func removeLayoutGuide(UILayoutGuide)
Removes the specified layout guide from the view.
https://developer.apple.com/documentation/uikit/uiview/layoutmarginsguide
https://developer.apple.com/documentation/uikit/uiview/readablecontentguide
- UIKit
- UIView
- readableContentGuide
Instance Property
readableContentGuide
A layout guide representing an area with a readable width within the view.
@MainActor var readableContentGuide: UILayoutGuide { get }
Discussion
This layout guide defines an area that can easily be read without forcing users to move their head to track the lines. The readable content area follows the following rules:
-
The readable content guide never extends beyond the view’s layout margin guide.
-
The readable content guide is vertically centered inside the layout margin guide.
-
The readable content guide’s width is equal to or less than the readable width defined for the current dynamic text size.
Use the readable content guide to lay out a single column of text. If you are laying out multiple columns, you can use the guide’s width to determine the optimal width for your columns.
See Also
Working with layout guides
func addLayoutGuide(UILayoutGuide)
Adds the specified layout guide to the view.
var layoutGuides: [UILayoutGuide]
The array of layout guide objects owned by this view.
var layoutMarginsGuide: UILayoutGuide
A layout guide representing the view’s margins.
func removeLayoutGuide(UILayoutGuide)
Removes the specified layout guide from the view.
https://developer.apple.com/documentation/uikit/uiview/removelayoutguide(_:)
https://developer.apple.com/documentation/uikit/uiview/systemlayoutsizefitting(_:)
https://developer.apple.com/documentation/uikit/uiview/systemlayoutsizefitting(_:withhorizontalfittingpriority:verticalfittingpriority:)
#app-main)
- UIKit
- UIView
- systemLayoutSizeFitting(_:withHorizontalFittingPriority:verticalFittingPriority:)
Instance Method
systemLayoutSizeFitting(_:withHorizontalFittingPriority:verticalFittingPriority:)
Returns the optimal size of the view based on its constraints and the specified fitting priorities.
tvOS
@MainActor func systemLayoutSizeFitting( _ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority
Parameters
targetSize
The size that you prefer for the view. To obtain a view that is as small as possible, specify the constant layoutFittingCompressedSize. To obtain a view that is as large as possible, specify the constant layoutFittingExpandedSize.
horizontalFittingPriority
The priority for horizontal constraints. Specify fittingSizeLevel to get a width that is as close as possible to the width value of targetSize.
verticalFittingPriority
The priority for vertical constraints. Specify fittingSizeLevel to get a height that is as close as possible to the height value of targetSize.
Return Value
The optimal size for the view based on the provided constraint priorities.
Discussion
Use this method when you want to prioritize the view’s constraints when determining the best possible size of the view. This method does not actually change the size of the view.
See Also
Measuring in Auto Layout
Returns the optimal size of the view based on its current constraints.
var intrinsicContentSize: CGSize
The natural size for the receiving view, considering only properties of the view itself.
func invalidateIntrinsicContentSize()
Invalidates the view’s intrinsic content size.
Returns the priority with which a view resists being made smaller than its intrinsic size.
func setContentCompressionResistancePriority(UILayoutPriority, for: NSLayoutConstraint.Axis)
Sets the priority with which a view resists being made smaller than its intrinsic size.
Returns the priority with which a view resists being made larger than its intrinsic size.
func setContentHuggingPriority(UILayoutPriority, for: NSLayoutConstraint.Axis)
Sets the priority with which a view resists being made larger than its intrinsic size.
https://developer.apple.com/documentation/uikit/uiview/intrinsiccontentsize
https://developer.apple.com/documentation/uikit/uiview/invalidateintrinsiccontentsize()
#app-main)
- UIKit
- UIView
- invalidateIntrinsicContentSize()
Instance Method
invalidateIntrinsicContentSize()
Invalidates the view’s intrinsic content size.
tvOS
@MainActor func invalidateIntrinsicContentSize()
Discussion
Call this when something changes in your custom view that invalidates its intrinsic content size. This allows the constraint-based layout system to take the new intrinsic content size into account in its next layout pass.
See Also
Measuring in Auto Layout
Returns the optimal size of the view based on its current constraints.
Returns the optimal size of the view based on its constraints and the specified fitting priorities.
var intrinsicContentSize: CGSize
The natural size for the receiving view, considering only properties of the view itself.
Returns the priority with which a view resists being made smaller than its intrinsic size.
func setContentCompressionResistancePriority(UILayoutPriority, for: NSLayoutConstraint.Axis)
Sets the priority with which a view resists being made smaller than its intrinsic size.
Returns the priority with which a view resists being made larger than its intrinsic size.
func setContentHuggingPriority(UILayoutPriority, for: NSLayoutConstraint.Axis)
Sets the priority with which a view resists being made larger than its intrinsic size.
https://developer.apple.com/documentation/uikit/uiview/contentcompressionresistancepriority(for:)
https://developer.apple.com/documentation/uikit/uiview/setcontentcompressionresistancepriority(_:for:)
#app-main)
- UIKit
- UIView
- setContentCompressionResistancePriority(_:for:)
Instance Method
setContentCompressionResistancePriority(_:for:)
Sets the priority with which a view resists being made smaller than its intrinsic size.
tvOS
@MainActor func setContentCompressionResistancePriority( _ priority: UILayoutPriority, for axis: NSLayoutConstraint.Axis )
Parameters
priority
The new priority.
axis
The axis for which the compression resistance priority should be set.
Discussion
Custom views should set default values for both orientations on creation, based on their content, typically to UILayoutPriorityDefaultLow or UILayoutPriorityDefaultHigh. When creating user interfaces, the layout designer can modify these priorities for specific views when the overall layout design requires different tradeoffs than the natural priorities of the views being used in the interface.
Subclasses should not override this method.
See Also
Measuring in Auto Layout
Returns the optimal size of the view based on its current constraints.
Returns the optimal size of the view based on its constraints and the specified fitting priorities.
var intrinsicContentSize: CGSize
The natural size for the receiving view, considering only properties of the view itself.
func invalidateIntrinsicContentSize()
Invalidates the view’s intrinsic content size.
Returns the priority with which a view resists being made smaller than its intrinsic size.
Returns the priority with which a view resists being made larger than its intrinsic size.
func setContentHuggingPriority(UILayoutPriority, for: NSLayoutConstraint.Axis)
Sets the priority with which a view resists being made larger than its intrinsic size.
https://developer.apple.com/documentation/uikit/uiview/contenthuggingpriority(for:)
#app-main)
- UIKit
- UIView
- contentHuggingPriority(for:)
Instance Method
contentHuggingPriority(for:)
Returns the priority with which a view resists being made larger than its intrinsic size.
tvOS
@MainActor
Parameters
axis
The axis of the view that might be enlarged.
Return Value
The priority with which the view should resist being enlarged from its intrinsic size on the specified axis.
Discussion
The constraint-based layout system uses these priorities when determining the best layout for views that are encountering constraints that would require them to be larger than their intrinsic size.
See Also
Measuring in Auto Layout
Returns the optimal size of the view based on its current constraints.
Returns the optimal size of the view based on its constraints and the specified fitting priorities.
var intrinsicContentSize: CGSize
The natural size for the receiving view, considering only properties of the view itself.
func invalidateIntrinsicContentSize()
Invalidates the view’s intrinsic content size.
Returns the priority with which a view resists being made smaller than its intrinsic size.
func setContentCompressionResistancePriority(UILayoutPriority, for: NSLayoutConstraint.Axis)
Sets the priority with which a view resists being made smaller than its intrinsic size.
func setContentHuggingPriority(UILayoutPriority, for: NSLayoutConstraint.Axis)
Sets the priority with which a view resists being made larger than its intrinsic size.
https://developer.apple.com/documentation/uikit/uiview/setcontenthuggingpriority(_:for:)
https://developer.apple.com/documentation/uikit/uiview/alignmentrectinsets
- UIKit
- UIView
- alignmentRectInsets
Instance Property
alignmentRectInsets
The insets from the view’s frame that define its alignment rectangle.
tvOS
@MainActor var alignmentRectInsets: UIEdgeInsets { get }
Discussion
The default value of this property is an UIEdgeInsets structure with zero values. Custom views that draw ornamentation around their content should use this property to return insets that align with the edges of the content, excluding the ornamentation. This allows the constraint-based layout system to align views based on their content, rather than just their frame.
Custom views whose content location can’t be expressed by a simple set of insets should override alignmentRect(forFrame:) and frame(forAlignmentRect:) to describe their custom transform between alignment rectangle and frame.
See Also
Aligning views in Auto Layout
Returns the view’s alignment rectangle for a given frame.
Returns the view’s frame for a given alignment rectangle.
var forFirstBaselineLayout: UIView
Returns a view used to satisfy first baseline constraints.
var forLastBaselineLayout: UIView
Returns a view used to satisfy last baseline constraints.
https://developer.apple.com/documentation/uikit/uiview/forfirstbaselinelayout
- UIKit
- UIView
- forFirstBaselineLayout
Instance Property
forFirstBaselineLayout
Returns a view used to satisfy first baseline constraints.
@MainActor var forFirstBaselineLayout: UIView { get }
Discussion
For views with multiple rows of text, the first baseline is the baseline for the topmost row.
When you make a constraint to a view’s NSLayoutConstraint.Attribute.firstBaseline attribute, Auto Layout uses the baseline of the view returned by this method. If that view does not have a baseline, Auto Layout uses the view’s top edge.
Override this property to return a text-based subview (for example, UILabel or a nonscrolling UITextView). The returned view must be a subview of the receiver. The default implementation returns the value contained by forLastBaselineLayout.
See Also
Aligning views in Auto Layout
Returns the view’s alignment rectangle for a given frame.
Returns the view’s frame for a given alignment rectangle.
var alignmentRectInsets: UIEdgeInsets
The insets from the view’s frame that define its alignment rectangle.
var forLastBaselineLayout: UIView
Returns a view used to satisfy last baseline constraints.
https://developer.apple.com/documentation/uikit/uiview/forlastbaselinelayout
- UIKit
- UIView
- forLastBaselineLayout
Instance Property
forLastBaselineLayout
Returns a view used to satisfy last baseline constraints.
@MainActor var forLastBaselineLayout: UIView { get }
Discussion
For views with multiple rows of text, the last baseline is the baseline for the bottommost row.
When you make a constraint to a view’s NSLayoutConstraint.Attribute.lastBaseline attribute, Auto Layout uses the baseline of the view returned by this method. If that view does not have a baseline, Auto Layout uses the view’s bottom edge.
Override this property to return a text-based subview (for example, UILabel or a nonscrolling UITextView). The returned view must be a subview of the receiver. The default implementation returns the receiving view.
See Also
Aligning views in Auto Layout
Returns the view’s alignment rectangle for a given frame.
Returns the view’s frame for a given alignment rectangle.
var alignmentRectInsets: UIEdgeInsets
The insets from the view’s frame that define its alignment rectangle.
var forFirstBaselineLayout: UIView
Returns a view used to satisfy first baseline constraints.
https://developer.apple.com/documentation/uikit/uiview/needsupdateconstraints()
https://developer.apple.com/documentation/uikit/uiview/setneedsupdateconstraints()
#app-main)
- UIKit
- UIView
- setNeedsUpdateConstraints()
Instance Method
setNeedsUpdateConstraints()
Controls whether the view’s constraints need updating.
tvOS
@MainActor func setNeedsUpdateConstraints()
Discussion
When a property of your custom view changes in a way that would impact constraints, you can call this method to indicate that the constraints need to be updated at some point in the future. The system will then call updateConstraints() as part of its normal layout pass. Use this as an optimization tool to batch constraint changes. Updating constraints all at once just before they are needed ensures that you don’t needlessly recalculate constraints when multiple changes are made to your view in between layout passes.
See Also
Triggering Auto Layout
A Boolean value that determines whether the view’s constraints need updating.
func updateConstraints()
Updates constraints for the view.
func updateConstraintsIfNeeded()
Updates the constraints for the receiving view and its subviews.
https://developer.apple.com/documentation/uikit/uiview/updateconstraintsifneeded()
#app-main)
- UIKit
- UIView
- updateConstraintsIfNeeded()
Instance Method
updateConstraintsIfNeeded()
Updates the constraints for the receiving view and its subviews.
tvOS
@MainActor func updateConstraintsIfNeeded()
Discussion
Whenever a new layout pass is triggered for a view, the system invokes this method to ensure that any constraints for the view and its subviews are updated with information from the current view hierarchy and its constraints. This method is called automatically by the system, but may be invoked manually if you need to examine the most up to date constraints.
Subclasses should not override this method.
See Also
Triggering Auto Layout
A Boolean value that determines whether the view’s constraints need updating.
func setNeedsUpdateConstraints()
Controls whether the view’s constraints need updating.
func updateConstraints()
Updates constraints for the view.
https://developer.apple.com/documentation/uikit/uiview/hasambiguouslayout
- UIKit
- UIView
- hasAmbiguousLayout
Instance Property
hasAmbiguousLayout
A Boolean value that determines whether the constraints impacting the layout of the view incompletely specify the location of the view.
tvOS
@MainActor var hasAmbiguousLayout: Bool { get }
Discussion
The value of this property is true if the view’s location is incompletely specified, false otherwise.
If there aren’t enough constraints in the system to uniquely determine layout, the layout is considered ambiguous. For example, if the only constraint in the system is x = y + 100, the layout is ambiguous because there are many possible values for x and y. UIKit does not automatically detect every ambiguous layout, so you may need to look for symptoms of ambiguity, such as views that jump from place to place, or that are in the wrong place.
This property should only be used for debugging constraint-based layout. No app should ship with usage of this property as part of its operation.
See Also
Debugging Auto Layout
Returns the constraints impacting the layout of the view for a given axis.
func exerciseAmbiguityInLayout()
Randomly changes the frame of a view with an ambiguous layout between the different valid values.
https://developer.apple.com/documentation/uikit/uiview/exerciseambiguityinlayout()
#app-main)
- UIKit
- UIView
- exerciseAmbiguityInLayout()
Instance Method
exerciseAmbiguityInLayout()
Randomly changes the frame of a view with an ambiguous layout between the different valid values.
tvOS
@MainActor func exerciseAmbiguityInLayout()
Discussion
This method randomly changes the frame of a view with an ambiguous layout between its different valid values, causing the view to move in the interface. This makes it easy to visually identify what the valid frames are and may enable the developer to discern what constraints need to be added to the layout to fully specify a location for the view.
This method should only be used for debugging constraint-based layout. No application should ship with calls to this method as part of its operation.
See Also
Debugging Auto Layout
Returns the constraints impacting the layout of the view for a given axis.
var hasAmbiguousLayout: Bool
A Boolean value that determines whether the constraints impacting the layout of the view incompletely specify the location of the view.
https://developer.apple.com/documentation/uikit/uiview/contentmode-swift.enum
- UIKit
- UIView
- UIView.ContentMode
Enumeration
UIView.ContentMode
Options to specify how a view adjusts its content when its size changes.
iOSiPadOSMac CatalysttvOSvisionOS
enum ContentMode
Topics
Constants
case scaleToFill
The option to scale the content to fit the size of itself by changing the aspect ratio of the content if necessary.
case scaleAspectFit
The option to scale the content to fit the size of the view by maintaining the aspect ratio. Any remaining area of the view’s bounds is transparent.
case scaleAspectFill
The option to scale the content to fill the size of the view. Some portion of the content may be clipped to fill the view’s bounds.
case redraw
The option to redisplay the view when the bounds change by invoking the setNeedsDisplay() method.
case center
The option to center the content in the view’s bounds, keeping the proportions the same.
case top
The option to center the content aligned at the top in the view’s bounds.
case bottom
The option to center the content aligned at the bottom in the view’s bounds.
case left
The option to align the content on the left of the view.
case right
The option to align the content on the right of the view.
case topLeft
The option to align the content in the top-left corner of the view.
case topRight
The option to align the content in the top-right corner of the view.
case bottomLeft
The option to align the content in the bottom-left corner of the view.
case bottomRight
The option to align the content in the bottom-right corner of the view.
Initializers
init?(rawValue: Int)
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Configuring the resizing behavior
var contentMode: UIView.ContentMode
A flag used to determine how a view lays out its content when its bounds change.
Asks the view to calculate and return the size that best fits the specified size.
func sizeToFit()
Resizes and moves the receiver view so it just encloses its subviews.
var autoresizesSubviews: Bool
A Boolean value that determines whether the receiver automatically resizes its subviews when its bounds change.
var autoresizingMask: UIView.AutoresizingMask
An integer bit mask that determines how the receiver resizes itself when its superview’s bounds change.
https://developer.apple.com/documentation/uikit/uiview/sizethatfits(_:)
https://developer.apple.com/documentation/uikit/uiview/sizetofit()
https://developer.apple.com/documentation/uikit/uiview/autoresizessubviews
- UIKit
- UIView
- autoresizesSubviews
Instance Property
autoresizesSubviews
A Boolean value that determines whether the receiver automatically resizes its subviews when its bounds change.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor var autoresizesSubviews: Bool { get set }
Discussion
When set to true, the receiver adjusts the size of its subviews when its bounds change. The default value is true.
See Also
Configuring the resizing behavior
var contentMode: UIView.ContentMode
A flag used to determine how a view lays out its content when its bounds change.
enum ContentMode
Options to specify how a view adjusts its content when its size changes.
Asks the view to calculate and return the size that best fits the specified size.
func sizeToFit()
Resizes and moves the receiver view so it just encloses its subviews.
var autoresizingMask: UIView.AutoresizingMask
An integer bit mask that determines how the receiver resizes itself when its superview’s bounds change.
https://developer.apple.com/documentation/uikit/uiview/layoutsubviews()
#app-main)
- UIKit
- UIView
- layoutSubviews()
Instance Method
layoutSubviews()
Lays out subviews.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor func layoutSubviews()
Discussion
The default implementation of this method does nothing on iOS 5.1 and earlier. Otherwise, the default implementation uses any constraints you’ve set to determine the size and position of any subviews.
Subclasses can override this method as needed to perform more precise layout of their subviews. You should override this method only if the autoresizing and constraint-based behaviors of the subviews don’t offer the behavior you want. You can use your implementation to set the frame rectangles of your subviews directly.
You shouldn’t call this method directly. If you want to force a layout update, call the setNeedsLayout() method instead to do so prior to the next drawing update. If you want to update the layout of your views immediately, call the layoutIfNeeded() method.
In iOS 18 and later, UIKit supports automatic trait tracking inside this method for traits from this view’s traitCollection. For more information, see Automatic trait tracking.
See Also
Views
func updateProperties()
Override point for subclasses to update properties of this view. Never call this method directly; use setNeedsUpdateProperties to schedule an update.
Beta
func setNeedsUpdateProperties()
Call to manually request a properties update for the view. Multiple requests may be coalesced into a single update alongside the next layout pass.
func updatePropertiesIfNeeded()
Forces an immediate properties update for this view (and its view controller, if applicable) and any subviews, including any view controllers or views in its subtree.
func updateConstraints()
Updates constraints for the view.
func draw(CGRect)
Draws the view’s image within the passed-in rectangle.
struct Properties
https://developer.apple.com/documentation/uikit/uiview/setneedslayout()
https://developer.apple.com/documentation/uikit/uiview/layoutifneeded()
#app-main)
- UIKit
- UIView
- layoutIfNeeded()
Instance Method
layoutIfNeeded()
Lays out the subviews immediately, if layout updates are pending.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor func layoutIfNeeded()
Discussion
Use this method to force the view to update its layout immediately. When using Auto Layout, the layout engine updates the position of views as needed to satisfy changes in constraints. Using the view that receives the message as the root view, this method lays out the view subtree starting at the root. If no layout updates are pending, this method exits without modifying the layout or calling any layout-related callbacks.
See Also
Laying out subviews
func layoutSubviews()
Lays out subviews.
func setNeedsLayout()
Invalidates the current layout of the receiver and triggers a layout update during the next update cycle.
class var requiresConstraintBasedLayout: Bool
A Boolean value that indicates whether the receiver depends on the constraint-based layout system.
var translatesAutoresizingMaskIntoConstraints: Bool
A Boolean value that determines whether the view’s autoresizing mask is translated into Auto Layout constraints.
https://developer.apple.com/documentation/uikit/uiview/translatesautoresizingmaskintoconstraints
- UIKit
- UIView
- translatesAutoresizingMaskIntoConstraints
Instance Property
translatesAutoresizingMaskIntoConstraints
A Boolean value that determines whether the view’s autoresizing mask is translated into Auto Layout constraints.
tvOS
@MainActor var translatesAutoresizingMaskIntoConstraints: Bool { get set }
Discussion
If this property’s value is true, the system creates a set of constraints that duplicate the behavior specified by the view’s autoresizing mask. This also lets you modify the view’s size and location using the view’s frame, bounds, or center properties, allowing you to create a static, frame-based layout within Auto Layout.
Note that the autoresizing mask constraints fully specify the view’s size and position; therefore, you cannot add additional constraints to modify this size or position without introducing conflicts. If you want to use Auto Layout to dynamically calculate the size and position of your view, you must set this property to false, and then provide a non ambiguous, nonconflicting set of constraints for the view.
By default, the property is set to true for any view you programmatically create. If you add views in Interface Builder, the system automatically sets this property to false.
See Also
Laying out subviews
func layoutSubviews()
Lays out subviews.
func setNeedsLayout()
Invalidates the current layout of the receiver and triggers a layout update during the next update cycle.
func layoutIfNeeded()
Lays out the subviews immediately, if layout updates are pending.
class var requiresConstraintBasedLayout: Bool
A Boolean value that indicates whether the receiver depends on the constraint-based layout system.
https://developer.apple.com/documentation/uikit/uiview/layoutregion
- UIKit
- UIView
- UIView.LayoutRegion
Structure
UIView.LayoutRegion
Mac Catalyst
struct LayoutRegion
Topics
Enumerations
enum AdaptivityAxis
Relationships
Conforms To
EquatableHashable
See Also
Accessing insets and layout guides
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uiview/directionaledgeinsets(for:)
#app-main)
- UIKit
- UIView
- directionalEdgeInsets(for:)
Instance Method
directionalEdgeInsets(for:)
Mac Catalyst
@MainActor @preconcurrency
See Also
Accessing insets and layout guides
struct LayoutRegion
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uiview/edgeinsets(for:)
#app-main)
- UIKit
- UIView
- edgeInsets(for:)
Instance Method
edgeInsets(for:)
Mac Catalyst
@MainActor @preconcurrency
See Also
Accessing insets and layout guides
struct LayoutRegion
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uiview/layoutguide(for:)
#app-main)
- UIKit
- UIView
- layoutGuide(for:)
Instance Method
layoutGuide(for:)
Mac Catalyst
@MainActor @preconcurrency
See Also
Accessing insets and layout guides
struct LayoutRegion
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uiview/overrideuserinterfacestyle
- UIKit
- UIView
- overrideUserInterfaceStyle
Instance Property
overrideUserInterfaceStyle
The user interface style adopted by the view and all of its subviews.
@MainActor var overrideUserInterfaceStyle: UIUserInterfaceStyle { get set }
Mentioned in
Choosing a specific interface style for your iOS app
Discussion
Use this property to force the view to always adopt a light or dark interface style. The default value of this property is UIUserInterfaceStyle.unspecified, which causes the view to inherit the interface style from a parent view or view controller. If you assign a different value, the new style applies to the view and all of the subviews owned by the same view controller. (If the view hierarchy contains the root view of an embedded child view controller, the child view controller and its views do not inherit the interface style.) If the view is a UIWindow object, the new style applies to everything in the window, including the root view controller and all presented content.
See Also
Adjusting the user interface
var semanticContentAttribute: UISemanticContentAttribute
A semantic description of the view’s contents, used to determine whether the view should be flipped when switching between left-to-right and right-to-left layouts.
var effectiveUserInterfaceLayoutDirection: UIUserInterfaceLayoutDirection
The user interface layout direction appropriate for arranging the immediate content of the view.
Returns the user interface direction for the given semantic content attribute.
Returns the layout direction implied by the specified semantic content attribute, relative to the specified layout direction.
https://developer.apple.com/documentation/uikit/uiview/semanticcontentattribute
- UIKit
- UIView
- semanticContentAttribute
Instance Property
semanticContentAttribute
A semantic description of the view’s contents, used to determine whether the view should be flipped when switching between left-to-right and right-to-left layouts.
@MainActor var semanticContentAttribute: UISemanticContentAttribute { get set }
Discussion
Some views should not flip when switching between left-to-right and right-to-left layouts. For example, the view is part of the playback controls or represents physical directions (up, down, left, right) that don’t change. Instead of thinking about whether or not a view should change its orientation, select the semantic content attribute that best describes your view.
When creating a view that contains subviews, you can use the userInterfaceLayoutDirection(for:) class method to determine whether the subviews should be flipped, and lay out the views in the appropriate order.
For a list of possible values, see UISemanticContentAttribute.
See Also
Adjusting the user interface
var overrideUserInterfaceStyle: UIUserInterfaceStyle
The user interface style adopted by the view and all of its subviews.
var effectiveUserInterfaceLayoutDirection: UIUserInterfaceLayoutDirection
The user interface layout direction appropriate for arranging the immediate content of the view.
Returns the user interface direction for the given semantic content attribute.
Returns the layout direction implied by the specified semantic content attribute, relative to the specified layout direction.
https://developer.apple.com/documentation/uikit/uiview/effectiveuserinterfacelayoutdirection
- UIKit
- UIView
- effectiveUserInterfaceLayoutDirection
Instance Property
effectiveUserInterfaceLayoutDirection
The user interface layout direction appropriate for arranging the immediate content of the view.
@MainActor var effectiveUserInterfaceLayoutDirection: UIUserInterfaceLayoutDirection { get }
Discussion
When a view’s immediate content is being arranged or drawn, you should always consult the value of this property. In addition, note that you can’t assume that the value propagates through the view’s subtree.
See Also
Adjusting the user interface
var overrideUserInterfaceStyle: UIUserInterfaceStyle
The user interface style adopted by the view and all of its subviews.
var semanticContentAttribute: UISemanticContentAttribute
A semantic description of the view’s contents, used to determine whether the view should be flipped when switching between left-to-right and right-to-left layouts.
Returns the user interface direction for the given semantic content attribute.
Returns the layout direction implied by the specified semantic content attribute, relative to the specified layout direction.
https://developer.apple.com/documentation/uikit/uiview/userinterfacelayoutdirection(for:)
https://developer.apple.com/documentation/uikit/uiview/userinterfacelayoutdirection(for:relativeto:)
#app-main)
- UIKit
- UIView
- userInterfaceLayoutDirection(for:relativeTo:)
Type Method
userInterfaceLayoutDirection(for:relativeTo:)
Returns the layout direction implied by the specified semantic content attribute, relative to the specified layout direction.
@MainActor class func userInterfaceLayoutDirection( for semanticContentAttribute: UISemanticContentAttribute, relativeTo layoutDirection: UIUserInterfaceLayoutDirection
Parameters
semanticContentAttribute
The semantic content attribute for a view.
layoutDirection
The user interface layout direction ( UIUserInterfaceLayoutDirection.leftToRight or UIUserInterfaceLayoutDirection.rightToLeft).
Return Value
The layout direction implied by the semantic content attribute and relative to the layout direction.
Discussion
For example, when this method is passed a layout direction of UIUserInterfaceLayoutDirection.rightToLeft and a semantic content attribute of UISemanticContentAttribute.playback, it returns UIUserInterfaceLayoutDirection.leftToRight. Although layout and drawing code can use this method to determine how to arrange elements, it might be easier to query the container view’s effectiveUserInterfaceLayoutDirection property instead.
See Also
Adjusting the user interface
var overrideUserInterfaceStyle: UIUserInterfaceStyle
The user interface style adopted by the view and all of its subviews.
var semanticContentAttribute: UISemanticContentAttribute
A semantic description of the view’s contents, used to determine whether the view should be flipped when switching between left-to-right and right-to-left layouts.
var effectiveUserInterfaceLayoutDirection: UIUserInterfaceLayoutDirection
The user interface layout direction appropriate for arranging the immediate content of the view.
Returns the user interface direction for the given semantic content attribute.
https://developer.apple.com/documentation/uikit/uiview/keyboardlayoutguide
- UIKit
- UIView
- keyboardLayoutGuide
Instance Property
keyboardLayoutGuide
A layout guide that tracks the keyboard’s position in your app’s layout.
@MainActor var keyboardLayoutGuide: UIKeyboardLayoutGuide { get }
See Also
Handling keyboard layout
class UIKeyboardLayoutGuide
A layout guide that represents the space the keyboard occupies in your app’s layout.
class UITrackingLayoutGuide
A layout guide that automatically activates and deactivates layout constraints depending on its proximity to edges.
https://developer.apple.com/documentation/uikit/uiview/addinteraction(_:)
#app-main)
- UIKit
- UIView
- addInteraction(_:)
Instance Method
addInteraction(_:)
Adds an interaction to the view.
@MainActor func addInteraction(_ interaction: any UIInteraction)
Parameters
interaction
The interaction object to add to the view.
See Also
Adding and removing interactions
func removeInteraction(any UIInteraction)
Removes an interaction from the view.
var interactions: [any UIInteraction]
The array of interactions for the view.
protocol UIInteraction
The protocol that an interaction implements to access the view that owns it.
https://developer.apple.com/documentation/uikit/uiview/removeinteraction(_:)
https://developer.apple.com/documentation/uikit/uiinteraction
https://developer.apple.com/documentation/uikit/uiview/contentscalefactor
https://developer.apple.com/documentation/uikit/uiview/tintcolordidchange()
https://developer.apple.com/documentation/uikit/uiview/invalidating
- UIKit
- UIView
- UIView.Invalidating
Structure
UIView.Invalidating
A property wrapper that notifies the system that a property value change has invalidated an aspect of the containing view.
Mac CatalystvisionOSSwift 5.1+
@propertyWrapper
Overview
Use this wrapper when a change in the property value invalidates the display, layout, configuration, constraints, or intrinsic sizing of a view. This wrapper performs any actions necessary to notify the system that your view is invalid and requires an update. The actions depend on the invalidation types you specify. For more information on available invalidation types, see UIViewInvalidating.
The following example uses the UIView.Invalidating wrapper with the display type on the property badgeColor and the display and layout type on the property badgePosition.
class MyView: UIView { @Invalidating(.display) var badgeColor: UIColor
@Invalidating(.display, .layout) var badgePosition: UIRectEdge }
When you change the badge color, the property wrapper calls setNeedsDisplay(), causing the system to redraw the view. When you change the badge position, the property wrapper also calls setNeedsLayout(), causing the system to update the view’s subviews before it redraws.
Functions such as setNeedsDisplay() and setNeedsLayout() perform changes on the next update cycle. You can make changes to multiple properties and views before any of those views update. Consolidating the updates to one update cycle is usually better for performance.
Topics
Creating an Invalidating Property Wrapper
init(wrappedValue: Value, InvalidationType)
Creates a property wrapper that notifies the system when a change in the property value invalidates an aspect of the containing view.
Creates a property wrapper that notifies the system when a change in the property value invalidates aspects of the containing view.
See Also
Updating the view when property values change
protocol UIViewInvalidating
Implements a type of invalidation that can occur on a view that requires an update.
https://developer.apple.com/documentation/uikit/uiviewinvalidating
https://developer.apple.com/documentation/uikit/uiview/viewprintformatter()
https://developer.apple.com/documentation/uikit/uiview/addgesturerecognizer(_:)
https://developer.apple.com/documentation/uikit/uiview/removegesturerecognizer(_:)
https://developer.apple.com/documentation/uikit/uiview/canbecomefocused
- UIKit
- UIView
- canBecomeFocused
Instance Property
canBecomeFocused
A Boolean value that indicates whether the view is currently capable of being focused.
@MainActor var canBecomeFocused: Bool { get }
Discussion
The value of this property is true if the view can become focused; false otherwise.
By default, the value of this property is false. This property informs the focus engine if a view is capable of being focused. Sometimes even if a view returns true, a view may not be focusable for the following reasons:
-
The view is hidden.
-
The view has alpha set to 0.
-
The view has
userInteractionEnabledset tofalse. -
The view is not currently in the view hierarchy.
See Also
Working with focus
class var inheritedAnimationDuration: TimeInterval
Returns the inherited duration of the current animation.
var isFocused: Bool
A Boolean value that indicates whether the item is currently focused.
var focusGroupIdentifier: String?
The identifier of the focus group that this view belongs to.
var focusEffect: UIFocusEffect?
The visual effect to apply when the view becomes focused.
var focusGroupPriority: UIFocusGroupPriority
The importance of the item within a focus group, used by the focus system to determine the group’s primary item.
https://developer.apple.com/documentation/uikit/uiview/inheritedanimationduration
- UIKit
- UIView
- inheritedAnimationDuration
Type Property
inheritedAnimationDuration
Returns the inherited duration of the current animation.
@MainActor class var inheritedAnimationDuration: TimeInterval { get }
Return Value
The duration of the current animation.
Discussion
This method only returns a non-zero value if called within a UIView animation block.
See Also
Working with focus
var canBecomeFocused: Bool
A Boolean value that indicates whether the view is currently capable of being focused.
var isFocused: Bool
A Boolean value that indicates whether the item is currently focused.
var focusGroupIdentifier: String?
The identifier of the focus group that this view belongs to.
var focusEffect: UIFocusEffect?
The visual effect to apply when the view becomes focused.
var focusGroupPriority: UIFocusGroupPriority
The importance of the item within a focus group, used by the focus system to determine the group’s primary item.
https://developer.apple.com/documentation/uikit/uiview/isfocused
- UIKit
- UIView
- isFocused
Instance Property
isFocused
A Boolean value that indicates whether the item is currently focused.
@MainActor var isFocused: Bool { get }
Discussion
This is a convenience property that checks whether the item is equal to the value in the UIScreen class’s focusedView property.
See Also
Working with focus
var canBecomeFocused: Bool
A Boolean value that indicates whether the view is currently capable of being focused.
class var inheritedAnimationDuration: TimeInterval
Returns the inherited duration of the current animation.
var focusGroupIdentifier: String?
The identifier of the focus group that this view belongs to.
var focusEffect: UIFocusEffect?
The visual effect to apply when the view becomes focused.
var focusGroupPriority: UIFocusGroupPriority
The importance of the item within a focus group, used by the focus system to determine the group’s primary item.
https://developer.apple.com/documentation/uikit/uiview/focusgroupidentifier
- UIKit
- UIView
- focusGroupIdentifier
Instance Property
focusGroupIdentifier
The identifier of the focus group that this view belongs to.
@MainActor var focusGroupIdentifier: String? { get set }
Discussion
If this property is nil, subviews inherit their superview’s focus group.
See Also
Working with focus
var canBecomeFocused: Bool
A Boolean value that indicates whether the view is currently capable of being focused.
class var inheritedAnimationDuration: TimeInterval
Returns the inherited duration of the current animation.
var isFocused: Bool
A Boolean value that indicates whether the item is currently focused.
var focusEffect: UIFocusEffect?
The visual effect to apply when the view becomes focused.
var focusGroupPriority: UIFocusGroupPriority
The importance of the item within a focus group, used by the focus system to determine the group’s primary item.
https://developer.apple.com/documentation/uikit/uiview/focuseffect
- UIKit
- UIView
- focusEffect
Instance Property
focusEffect
The visual effect to apply when the view becomes focused.
@NSCopying @MainActor var focusEffect: UIFocusEffect? { get set }
Discussion
If this property is nil, the system doesn’t apply an effect when the view becomes focused.
See Also
Working with focus
var canBecomeFocused: Bool
A Boolean value that indicates whether the view is currently capable of being focused.
class var inheritedAnimationDuration: TimeInterval
Returns the inherited duration of the current animation.
var isFocused: Bool
A Boolean value that indicates whether the item is currently focused.
var focusGroupIdentifier: String?
The identifier of the focus group that this view belongs to.
var focusGroupPriority: UIFocusGroupPriority
The importance of the item within a focus group, used by the focus system to determine the group’s primary item.
https://developer.apple.com/documentation/uikit/uiview/focusgrouppriority
https://developer.apple.com/documentation/uikit/uiview/addmotioneffect(_:)
https://developer.apple.com/documentation/uikit/uiview/removemotioneffect(_:)
#app-main)
- UIKit
- UIView
- removeMotionEffect(_:)
Instance Method
removeMotionEffect(_:)
Stops applying a motion effect to the view.
tvOS
@MainActor func removeMotionEffect(_ effect: UIMotionEffect)
Parameters
effect
The motion effect.
Discussion
Any affected presentation values animate to their post-removal values using the present UIView animation context.
See Also
Using motion effects
func addMotionEffect(UIMotionEffect)
Begins applying a motion effect to the view.
var motionEffects: [UIMotionEffect]
The array of motion effects for the view.
https://developer.apple.com/documentation/uikit/uiview/hoverstyle
- UIKit
- UIView
- hoverStyle
Instance Property
hoverStyle
The hover style for the view.
@NSCopying @MainActor var hoverStyle: UIHoverStyle? { get set }
Discussion
The value of this property defaults to nil, which indicates that the view doesn’t have any hover effect. Subclasses can configure this style to use a different default value.
See Also
Managing the hover appearance
class UIHoverStyle
The hover style to apply to a view, including an effect and a shape to use for displaying that effect.
class UIHoverEffectLayer
https://developer.apple.com/documentation/uikit/uihoverstyle
- UIKit
- UIHoverStyle
Class
UIHoverStyle
The hover style to apply to a view, including an effect and a shape to use for displaying that effect.
@MainActor class UIHoverStyle
Topics
Creating a hover style
convenience init(effect: some UIHoverEffect, shape: UIShape?)
Creates a hover style with the provided effect and shape.
convenience init(shape: UIShape?)
Creates a hover style with the provided shape and an automatic hover effect.
Specifying a hover shape
var shape: UIShape?
The shape to use for the hover effect.
struct UIShape
An abstract representation of a shape.
Specifying a hover effect
var effect: any UIHoverEffect
The effect to apply to the view with this style.
struct UIHoverAutomaticEffect
A system-default hover effect that automatically selects the appropriate effect based on the view to which it applies.
struct UIHoverHighlightEffect
An effect that applies a highlight to the view on hover.
struct UIHoverLiftEffect
An effect that can visually lift the view on hover where appropriate.
protocol UIHoverEffect
A hover effect that can apply to a view through a hover style.
Managing the state of the hover effect
var isEnabled: Bool
A Boolean value that determines whether the hover effect is active.
Relationships
Inherits From
NSObject
Inherited By
UIPointerStyle
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCopyingNSObjectProtocol
See Also
Managing the hover appearance
var hoverStyle: UIHoverStyle?
The hover style for the view.
class UIHoverEffectLayer
https://developer.apple.com/documentation/uikit/uihovereffectlayer
- UIKit
- UIHoverEffectLayer
Class
UIHoverEffectLayer
@MainActor class UIHoverEffectLayer
Topics
Initializers
init(containerView: UIView, style: UIHoverStyle?)
Instance Properties
var containerView: UIView?
var hoverStyle: UIHoverStyle
Relationships
Inherits From
CALayer
Conforms To
CAMediaTimingCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSSecureCodingSendableSendableMetatype
See Also
Managing the hover appearance
var hoverStyle: UIHoverStyle?
The hover style for the view.
class UIHoverStyle
The hover style to apply to a view, including an effect and a shape to use for displaying that effect.
https://developer.apple.com/documentation/uikit/uiview/minimumcontentsizecategory
https://developer.apple.com/documentation/uikit/uiview/maximumcontentsizecategory
- UIKit
- UIView
- maximumContentSizeCategory
Instance Property
maximumContentSizeCategory
The maximum content size category for the view and its subviews.
@MainActor var maximumContentSizeCategory: UIContentSizeCategory? { get set }
Discussion
Use this property to limit which content size categories your view hierarchy supports. The limit applies immediately after you set this value and when future content size category updates occur.
Set this property to nil to remove the maximum limit for the content size category.
See Also
Managing font-sizing preferences
var minimumContentSizeCategory: UIContentSizeCategory?
The minimum content size category for the view and its subviews.
var appliedContentSizeCategoryLimitsDescription: String
A string that lists each of the view’s superviews, its content size category, and whether that view has content size category limits.
https://developer.apple.com/documentation/uikit/uiview/appliedcontentsizecategorylimitsdescription
- UIKit
- UIView
- appliedContentSizeCategoryLimitsDescription
Instance Property
appliedContentSizeCategoryLimitsDescription
A string that lists each of the view’s superviews, its content size category, and whether that view has content size category limits.
@MainActor var appliedContentSizeCategoryLimitsDescription: String { get }
See Also
Managing font-sizing preferences
var minimumContentSizeCategory: UIContentSizeCategory?
The minimum content size category for the view and its subviews.
var maximumContentSizeCategory: UIContentSizeCategory?
The maximum content size category for the view and its subviews.
https://developer.apple.com/documentation/uikit/uiview/restorationidentifier
- UIKit
- UIView
- restorationIdentifier
Instance Property
restorationIdentifier
The identifier that determines whether the view supports state restoration.
tvOS
@MainActor var restorationIdentifier: String? { get set }
Discussion
This property indicates whether state information in the view should be preserved; it is also used to identify the view during the restoration process. The value of this property is nil by default, which indicates that the view’s state does not need to be saved. Assigning a string object to the property lets the owning view controller know that the view has relevant state information to save.
Assign a value to this property only if you are implementing a custom view that implements the encodeRestorableState(with:) and decodeRestorableState(with:) methods for saving and restoring state. You use those methods to write any view-specific state information and subsequently use that data to restore the view to its previous configuration.
See Also
Preserving and restoring state
func encodeRestorableState(with: NSCoder)
Encodes state-related information for the view.
func decodeRestorableState(with: NSCoder)
Decodes and restores state-related information for the view.
https://developer.apple.com/documentation/uikit/uiview/encoderestorablestate(with:)
#app-main)
- UIKit
- UIView
- encodeRestorableState(with:)
Instance Method
encodeRestorableState(with:)
Encodes state-related information for the view.
tvOS
@MainActor func encodeRestorableState(with coder: NSCoder)
Parameters
coder
The coder object to use to encode the state of the view.
Discussion
If your app supports state preservation, you can override this method for any views that have state information that should be saved between launches of your app. You should save only the data required to return the view to its current configuration. Do not save the view object itself and do not save any data that could be determined by other means at launch time.
Few views should need to save state information. Most views should just be configured using the data from their view controller. However, this method is available for those views that have user-configurable state that would be otherwise lost between app launches.
Your implementation of this method can encode other restorable view and view controller objects that it needs to reference. Encoding a restorable view or view controller writes that object’s restoration identifier to the coder. (That identifier is used during the decode process to locate the new version of the object.) If the view or view controller defines its own version of this method, that method is also called at some point so that the object can encode its own state.
Apart from views and view controllers, other objects follow the normal serialization process and must adopt the NSCoding protocol before they can be encoded. Encoding such objects embeds the object’s contents in the archive directly. During the decode process, a new object is created and initialized with the data from the archive.
It is recommended that you call super at some point during your implementation to give parent classes an opportunity to save their state information.
See Also
Preserving and restoring state
var restorationIdentifier: String?
The identifier that determines whether the view supports state restoration.
func decodeRestorableState(with: NSCoder)
Decodes and restores state-related information for the view.
https://developer.apple.com/documentation/uikit/uiview/decoderestorablestate(with:)
https://developer.apple.com/documentation/uikit/uiview/snapshotview(afterscreenupdates:)
https://developer.apple.com/documentation/uikit/uiview/resizablesnapshotview(from:afterscreenupdates:withcapinsets:)
#app-main)
- UIKit
- UIView
- resizableSnapshotView(from:afterScreenUpdates:withCapInsets:)
Instance Method
resizableSnapshotView(from:afterScreenUpdates:withCapInsets:)
Returns a snapshot view based on the specified contents of the current view, with stretchable insets.
tvOS
@MainActor func resizableSnapshotView( from rect: CGRect, afterScreenUpdates afterUpdates: Bool, withCapInsets capInsets: UIEdgeInsets
Parameters
rect
The portion of the view that you want to capture. The rectangle must be in the bounds coordinate space of the current view.
afterUpdates
A Boolean value that specifies whether the snapshot should be taken after recent changes have been incorporated. Pass the value false if you want to capture the screen in its current state, which might not include recent changes.
capInsets
The edge insets that define the stretchable portion of the returned view’s content. You can specify zero if you do not want the contents of the returned view to have a stretchable area.
Return Value
A new view object containing a snapshot of the current view’s rendered contents.
Discussion
This method very efficiently captures the current rendered appearance of a view and uses it to build a new snapshot view with stretchable insets. You can use the returned view as a visual stand-in for the current view in your app. For example, you might use a snapshot view for animations where updating a large view hierarchy might be expensive. Because the content is captured from the already rendered content, this method reflects the current visual appearance of the view and is not updated to reflect animations that are scheduled or in progress. However, calling this method is faster than trying to render the contents of the current view into a bitmap image yourself.
Because the returned snapshot is a view object, you can modify it and its layer object as needed. However, you cannot change the contents property of the snapshot view’s layer; attempts to do so fail silently. If the current view is not yet rendered, perhaps because it is not yet onscreen, the snapshot view has no visible content.
You can call this method on a previously generated snapshot to obtain a new snapshot. For example, you could do so after you change properties of a previous snapshot (such as its alpha value) and want a new snapshot that includes those changes.
If you want to apply a graphical effect, such as blur, to a snapshot, use the drawHierarchy(in:afterScreenUpdates:) method instead.
If you specify nonzero edge insets in the capInsets parameter, those values determine the returned snapshot’s stretchable content area.
See Also
Capturing a view snapshot
Returns a snapshot view based on the contents of the current view.
Renders a snapshot of the complete view hierarchy as visible onscreen into the current context.
https://developer.apple.com/documentation/uikit/uiview/drawhierarchy(in:afterscreenupdates:)
#app-main)
- UIKit
- UIView
- drawHierarchy(in:afterScreenUpdates:)
Instance Method
drawHierarchy(in:afterScreenUpdates:)
Renders a snapshot of the complete view hierarchy as visible onscreen into the current context.
tvOS
@MainActor func drawHierarchy( in rect: CGRect, afterScreenUpdates afterUpdates: Bool
Parameters
rect
A rectangle specified in the local coordinate system (bounds) of the view.
afterUpdates
A Boolean value that indicates whether the snapshot should be rendered after recent changes have been incorporated. Specify the value false if you want to render a snapshot in the view hierarchy’s current state, which might not include recent changes.
Return Value
Returns true if the snapshot is complete, or false if the snapshot is missing image data for any view in the hierarchy.
Discussion
Use this method when you want to apply a graphical effect, such as a blur, to a view snapshot. This method is not as fast as the snapshotView(afterScreenUpdates:) method.
See Also
Capturing a view snapshot
Returns a snapshot view based on the contents of the current view.
Returns a snapshot view based on the specified contents of the current view, with stretchable insets.
https://developer.apple.com/documentation/uikit/uiview/tag
- UIKit
- UIView
- tag
Instance Property
tag
An integer that you can use to identify view objects in your application.
tvOS
@MainActor var tag: Int { get set }
Discussion
The default value is 0. You can set the value of this tag and use that value to identify the view later.
See Also
Identifying the view at runtime
Returns the view whose tag matches the specified value.
https://developer.apple.com/documentation/uikit/uiview/viewwithtag(_:)
https://developer.apple.com/documentation/uikit/uiview/convert(_:to:)-1xizt
https://developer.apple.com/documentation/uikit/uiview/convert(_:from:)-8neo1
-8neo1#app-main)
- UIKit
- UIView
- convert(_:from:)
Instance Method
convert(_:from:)
Converts a point from the coordinate system of a given view to that of the receiver.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor func convert( _ point: CGPoint, from view: UIView?
Parameters
point
A point specified in the local coordinate system (bounds) of view.
view
The view with point in its coordinate system. If view is nil, this method instead converts from window base coordinates. Otherwise, both view and the receiver must belong to the same UIWindow object.
Return Value
The point converted to the local coordinate system (bounds) of the receiver.
See Also
Converting between view coordinate systems
Converts a point from the receiver’s coordinate system to that of the specified view.
Converts a rectangle from the receiver’s coordinate system to that of another view.
Converts a rectangle from the coordinate system of another view to that of the receiver.
https://developer.apple.com/documentation/uikit/uiview/convert(_:to:)-2kf3d
https://developer.apple.com/documentation/uikit/uiview/convert(_:from:)-7irzk
https://developer.apple.com/documentation/uikit/uiview/hittest(_:with:)
https://developer.apple.com/documentation/uikit/uiview/point(inside:with:)
https://developer.apple.com/documentation/uikit/uiview/endediting(_:)
#app-main)
- UIKit
- UIView
- endEditing(_:)
Instance Method
endEditing(_:)
Causes the view (or one of its embedded text fields) to resign the first responder status.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor
Parameters
force
Specify true to force the first responder to resign, regardless of whether it wants to do so.
Return Value
true if the view resigned the first responder status or false if it did not.
Discussion
This method looks at the current view and its subview hierarchy for the text field that is currently the first responder. If it finds one, it asks that text field to resign as first responder. If the force parameter is set to true, the text field is never even asked; it is forced to resign.
https://developer.apple.com/documentation/uikit/uiview/accessibilityignoresinvertcolors
- UIKit
- UIView
- accessibilityIgnoresInvertColors
Instance Property
accessibilityIgnoresInvertColors
A Boolean value indicating whether the view ignores an accessibility request to invert its colors.
@MainActor var accessibilityIgnoresInvertColors: Bool { get set }
Discussion
Inverting colors is often used to help users with light or color sensitivities to make bright colors darker. However, this behavior can have a destructive impact on images and videos. If inverting the colors would have a negative impact on your view’s content, set this property to true to prevent it from inverting its colors. Setting the property to true prevents the system from inverting the colors of the view and all of its subviews.
See Also
Modifying the accessibility behavior
var largeContentImage: UIImage?
An image that represents the view in the large content viewer.
var largeContentImageInsets: UIEdgeInsets
Insets to adjust the position of the view’s image so it appears centered in the large content viewer.
var largeContentTitle: String?
A string that describes the view in the large content viewer.
var scalesLargeContentImage: Bool
A Boolean value that indicates whether the large content viewer scales the item’s image to a larger size.
var showsLargeContentViewer: Bool
A Boolean value that indicates whether to show the view in the large content viewer.
https://developer.apple.com/documentation/uikit/uiview/largecontentimage
- UIKit
- UIView
- largeContentImage
Instance Property
largeContentImage
An image that represents the view in the large content viewer.
@MainActor var largeContentImage: UIImage? { get set }
Discussion
To present content in the large content viewer, you can provide either largeContentTitle or largeContentImage, or both.
This property defaults to an appropriate value for UIKit classes; otherwise, it’s nil.
See Also
Modifying the accessibility behavior
var accessibilityIgnoresInvertColors: Bool
A Boolean value indicating whether the view ignores an accessibility request to invert its colors.
var largeContentImageInsets: UIEdgeInsets
Insets to adjust the position of the view’s image so it appears centered in the large content viewer.
var largeContentTitle: String?
A string that describes the view in the large content viewer.
var scalesLargeContentImage: Bool
A Boolean value that indicates whether the large content viewer scales the item’s image to a larger size.
var showsLargeContentViewer: Bool
A Boolean value that indicates whether to show the view in the large content viewer.
https://developer.apple.com/documentation/uikit/uiview/largecontentimageinsets
- UIKit
- UIView
- largeContentImageInsets
Instance Property
largeContentImageInsets
Insets to adjust the position of the view’s image so it appears centered in the large content viewer.
@MainActor var largeContentImageInsets: UIEdgeInsets { get set }
Discussion
This property defaults to zero.
See Also
Modifying the accessibility behavior
var accessibilityIgnoresInvertColors: Bool
A Boolean value indicating whether the view ignores an accessibility request to invert its colors.
var largeContentImage: UIImage?
An image that represents the view in the large content viewer.
var largeContentTitle: String?
A string that describes the view in the large content viewer.
var scalesLargeContentImage: Bool
A Boolean value that indicates whether the large content viewer scales the item’s image to a larger size.
var showsLargeContentViewer: Bool
A Boolean value that indicates whether to show the view in the large content viewer.
https://developer.apple.com/documentation/uikit/uiview/largecontenttitle
- UIKit
- UIView
- largeContentTitle
Instance Property
largeContentTitle
A string that describes the view in the large content viewer.
@MainActor var largeContentTitle: String? { get set }
Discussion
To present content in the large content viewer, you can provide either largeContentTitle or largeContentImage, or both.
This property defaults to an appropriate value for UIKit classes; otherwise, it’s nil.
See Also
Modifying the accessibility behavior
var accessibilityIgnoresInvertColors: Bool
A Boolean value indicating whether the view ignores an accessibility request to invert its colors.
var largeContentImage: UIImage?
An image that represents the view in the large content viewer.
var largeContentImageInsets: UIEdgeInsets
Insets to adjust the position of the view’s image so it appears centered in the large content viewer.
var scalesLargeContentImage: Bool
A Boolean value that indicates whether the large content viewer scales the item’s image to a larger size.
var showsLargeContentViewer: Bool
A Boolean value that indicates whether to show the view in the large content viewer.
https://developer.apple.com/documentation/uikit/uiview/scaleslargecontentimage
- UIKit
- UIView
- scalesLargeContentImage
Instance Property
scalesLargeContentImage
A Boolean value that indicates whether the large content viewer scales the item’s image to a larger size.
@MainActor var scalesLargeContentImage: Bool { get set }
Discussion
If false, the viewer displays the image at its intrinsic size.
See Also
Modifying the accessibility behavior
var accessibilityIgnoresInvertColors: Bool
A Boolean value indicating whether the view ignores an accessibility request to invert its colors.
var largeContentImage: UIImage?
An image that represents the view in the large content viewer.
var largeContentImageInsets: UIEdgeInsets
Insets to adjust the position of the view’s image so it appears centered in the large content viewer.
var largeContentTitle: String?
A string that describes the view in the large content viewer.
var showsLargeContentViewer: Bool
A Boolean value that indicates whether to show the view in the large content viewer.
https://developer.apple.com/documentation/uikit/uiview/showslargecontentviewer
- UIKit
- UIView
- showsLargeContentViewer
Instance Property
showsLargeContentViewer
A Boolean value that indicates whether to show the view in the large content viewer.
@MainActor var showsLargeContentViewer: Bool { get set }
Discussion
For this property to take effect, the view must have a UILargeContentViewerInteraction.
See Also
Modifying the accessibility behavior
var accessibilityIgnoresInvertColors: Bool
A Boolean value indicating whether the view ignores an accessibility request to invert its colors.
var largeContentImage: UIImage?
An image that represents the view in the large content viewer.
var largeContentImageInsets: UIEdgeInsets
Insets to adjust the position of the view’s image so it appears centered in the large content viewer.
var largeContentTitle: String?
A string that describes the view in the large content viewer.
var scalesLargeContentImage: Bool
A Boolean value that indicates whether the large content viewer scales the item’s image to a larger size.
https://developer.apple.com/documentation/uikit/uiview/animate(springduration:bounce:initialspringvelocity:delay:options:animations:completion:)
#app-main)
- UIKit
- UIView
- animate(springDuration:bounce:initialSpringVelocity:delay:options:animations:completion:)
Type Method
animate(springDuration:bounce:initialSpringVelocity:delay:options:animations:completion:)
Animates changes to one or more views using a spring animation with the specified duration, bounce, initial velocity, delay, options, and completion handler.
Mac Catalyst
@MainActor @preconcurrency class func animate( springDuration duration: TimeInterval = 0.5, bounce: CGFloat = 0.0, initialSpringVelocity: CGFloat = 0.0, delay: TimeInterval = 0.0, options: UIView.AnimationOptions = [],
)
Discussion
See Also
Animating views
Animate changes to one or more views using the specified duration, delay, options, and completion handler.
Animate changes to one or more views using the specified duration and completion handler.
Animate changes to one or more views using the specified duration.
Creates a transition animation for the specified container view.
Creates a transition animation between the specified views using the given parameters.
Creates an animation block object that can be used to set up keyframe-based animations for the current view.
Specifies the timing and animation values for a single frame of a keyframe animation.
Performs a specified system-provided animation on one or more views, along with optional parallel animations that you define.
Performs a view animation using a timing curve corresponding to the motion of a physical spring.
Disables a view transition animation.
Repeats the specified animations a specific number of times, optionally running the animation forward and backward.
https://developer.apple.com/documentation/uikit/uiview/animate(withduration:delay:options:animations:completion:)
#app-main)
- UIKit
- UIView
- animate(withDuration:delay:options:animations:completion:)
Type Method
animate(withDuration:delay:options:animations:completion:)
Animate changes to one or more views using the specified duration, delay, options, and completion handler.
tvOS
@MainActor class func animate( withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions = [],
)
Parameters
duration
The total duration of the animations, measured in seconds. If you specify a negative value or 0, the changes are made without animating them.
delay
The amount of time (measured in seconds) to wait before beginning the animations. Specify a value of 0 to begin the animations immediately.
options
A mask of options indicating how you want to perform the animations. For a list of valid constants, see UIView.AnimationOptions.
animations
A block object containing the changes to commit to the views. This is where you programmatically change any animatable properties of the views in your view hierarchy. This block takes no parameters and has no return value. This parameter must not be NULL.
completion
A block object to be executed when the animation sequence ends. This block has no return value and takes a single Boolean argument that indicates whether or not the animations actually finished before the completion handler was called. If the duration of the animation is 0, this block is performed at the beginning of the next run loop cycle. This parameter may be NULL.
Discussion
This method initiates a set of animations to perform on the view. The block object in the animations parameter contains the code for animating the properties of one or more views.
During an animation, user interactions are temporarily disabled for the views being animated. (Prior to iOS 5, user interactions are disabled for the entire application.) If you want users to be able to interact with the views, include the allowUserInteraction constant in the options parameter.
See Also
Animating views
Animates changes to one or more views using a spring animation with the specified duration, bounce, initial velocity, delay, options, and completion handler.
Animate changes to one or more views using the specified duration and completion handler.
Animate changes to one or more views using the specified duration.
Creates a transition animation for the specified container view.
Creates a transition animation between the specified views using the given parameters.
Creates an animation block object that can be used to set up keyframe-based animations for the current view.
Specifies the timing and animation values for a single frame of a keyframe animation.
Performs a specified system-provided animation on one or more views, along with optional parallel animations that you define.
Performs a view animation using a timing curve corresponding to the motion of a physical spring.
Disables a view transition animation.
Repeats the specified animations a specific number of times, optionally running the animation forward and backward.
https://developer.apple.com/documentation/uikit/uiview/animate(withduration:animations:completion:)
https://developer.apple.com/documentation/uikit/uiview/animate(withduration:animations:)
#app-main)
- UIKit
- UIView
- animate(withDuration:animations:)
Type Method
animate(withDuration:animations:)
Animate changes to one or more views using the specified duration.
tvOS
@MainActor class func animate( withDuration duration: TimeInterval,
)
Parameters
duration
The total duration of the animations, measured in seconds. If you specify a negative value or 0, the changes are made without animating them.
animations
A block object containing the changes to commit to the views. This is where you programmatically change any animatable properties of the views in your view hierarchy. This block takes no parameters and has no return value. This parameter must not be NULL.
Discussion
This method performs the specified animations immediately using the curveEaseInOut and UIViewAnimationOptionTransitionNone animation options.
During an animation, user interactions are temporarily disabled for the views being animated. (Prior to iOS 5, user interactions are disabled for the entire application.)
See Also
Animating views
Animates changes to one or more views using a spring animation with the specified duration, bounce, initial velocity, delay, options, and completion handler.
Animate changes to one or more views using the specified duration, delay, options, and completion handler.
Animate changes to one or more views using the specified duration and completion handler.
Creates a transition animation for the specified container view.
Creates a transition animation between the specified views using the given parameters.
Creates an animation block object that can be used to set up keyframe-based animations for the current view.
Specifies the timing and animation values for a single frame of a keyframe animation.
Performs a specified system-provided animation on one or more views, along with optional parallel animations that you define.
Performs a view animation using a timing curve corresponding to the motion of a physical spring.
Disables a view transition animation.
Repeats the specified animations a specific number of times, optionally running the animation forward and backward.
https://developer.apple.com/documentation/uikit/uiview/transition(with:duration:options:animations:completion:)
https://developer.apple.com/documentation/uikit/uiview/transition(from:to:duration:options:completion:)
#app-main)
- UIKit
- UIView
- transition(from:to:duration:options:completion:)
Type Method
transition(from:to:duration:options:completion:)
Creates a transition animation between the specified views using the given parameters.
tvOS
@MainActor class func transition( from fromView: UIView, to toView: UIView, duration: TimeInterval, options: UIView.AnimationOptions = [],
)
Parameters
fromView
The starting view for the transition. By default, this view is removed from its superview as part of the transition.
toView
The ending view for the transition. By default, this view is added to the superview of fromView as part of the transition.
duration
The duration of the transition animation, measured in seconds. If you specify a negative value or 0, the transition is made without animations.
options
A mask of options indicating how you want to perform the animations. For a list of valid constants, see UIView.AnimationOptions.
completion
A block object to be executed when the animation sequence ends. This block has no return value and takes a single Boolean argument that indicates whether or not the animations actually finished before the completion handler was called. If the duration of the animation is 0, this block is performed at the beginning of the next run loop cycle. This parameter may be NULL.
Discussion
This method provides a simple way to transition from the view in the fromView parameter to the view in the toView parameter. By default, the view in fromView is replaced in the view hierarchy by the view in toView. If both views are already part of your view hierarchy, you can include the showHideTransitionViews option in the options parameter to simply hide or show them.
This method modifies the views in their view hierarchy only. It does not modify your application’s view controllers in any way. For example, if you use this method to change the root view displayed by a view controller, it is your responsibility to update the view controller appropriately to handle the change.
The view transition starts immediately unless another animation is already in-flight, in which case it starts immediately after the current animation finishes.
During an animation, user interactions are temporarily disabled for the views being animated. (Prior to iOS 5, user interactions are disabled for the entire application.) If you want users to be able to interact with the views, include the allowUserInteraction constant in the options parameter.
See Also
Animating views
Animates changes to one or more views using a spring animation with the specified duration, bounce, initial velocity, delay, options, and completion handler.
Animate changes to one or more views using the specified duration, delay, options, and completion handler.
Animate changes to one or more views using the specified duration and completion handler.
Animate changes to one or more views using the specified duration.
Creates a transition animation for the specified container view.
Creates an animation block object that can be used to set up keyframe-based animations for the current view.
Specifies the timing and animation values for a single frame of a keyframe animation.
Performs a specified system-provided animation on one or more views, along with optional parallel animations that you define.
Performs a view animation using a timing curve corresponding to the motion of a physical spring.
Disables a view transition animation.
Repeats the specified animations a specific number of times, optionally running the animation forward and backward.
https://developer.apple.com/documentation/uikit/uiview/animatekeyframes(withduration:delay:options:animations:completion:)
#app-main)
- UIKit
- UIView
- animateKeyframes(withDuration:delay:options:animations:completion:)
Type Method
animateKeyframes(withDuration:delay:options:animations:completion:)
Creates an animation block object that can be used to set up keyframe-based animations for the current view.
tvOS
@MainActor class func animateKeyframes( withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.KeyframeAnimationOptions = [],
) @MainActor class func animateKeyframes( withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.KeyframeAnimationOptions = [],
Parameters
duration
The duration of the overall animation, measured in seconds. If you specify a negative value or 0, changes are made immediately and without animations.
delay
Specifies the time (in seconds) to wait before starting the animation.
options
A mask of options indicating how you want to perform the animations. For a list of valid constants, see UIView.KeyframeAnimationOptions.
animations
A block object containing the changes to commit to the views. Typically, you call the addKeyframe(withRelativeStartTime:relativeDuration:animations:) method one or more times from inside this block. You may also change view values directly if you want those changes to animate over the full duration. This block takes no parameters and has no return value. Do not use a nil value for this parameter.
completion
A block object to be executed when the animation sequence ends. This block has no return value and takes a single Boolean argument that indicates whether or not the animations finished before the completion handler was called. If the duration of the animation is 0, this block is performed at the beginning of the next run loop cycle. You can use a nil value for this parameter.
Discussion
This method creates an animation block that you can use to set up a keyframe-based animation. The keyframes themselves are not part of the initial animation block you create using this method. Inside the animations block, you must add the keyframe time and animation data by calling the addKeyframe(withRelativeStartTime:relativeDuration:animations:) method one or more times. Adding keyframes causes the animation to animate the view from its current value to the value of the first keyframe, then to the value of the next keyframe, and so on at the times you specify.
If you do not add any keyframes in the animations block, the animation proceeds from start to end like a standard animation block. In other words, the system animates from the current view values to any new values over the specified duration.
See Also
Animating views
Animates changes to one or more views using a spring animation with the specified duration, bounce, initial velocity, delay, options, and completion handler.
Animate changes to one or more views using the specified duration, delay, options, and completion handler.
Animate changes to one or more views using the specified duration and completion handler.
Animate changes to one or more views using the specified duration.
Creates a transition animation for the specified container view.
Creates a transition animation between the specified views using the given parameters.
Specifies the timing and animation values for a single frame of a keyframe animation.
Performs a specified system-provided animation on one or more views, along with optional parallel animations that you define.
Performs a view animation using a timing curve corresponding to the motion of a physical spring.
Disables a view transition animation.
Repeats the specified animations a specific number of times, optionally running the animation forward and backward.
https://developer.apple.com/documentation/uikit/uiview/addkeyframe(withrelativestarttime:relativeduration:animations:)
#app-main)
- UIKit
- UIView
- addKeyframe(withRelativeStartTime:relativeDuration:animations:)
Type Method
addKeyframe(withRelativeStartTime:relativeDuration:animations:)
Specifies the timing and animation values for a single frame of a keyframe animation.
tvOS
@MainActor class func addKeyframe( withRelativeStartTime frameStartTime: Double, relativeDuration frameDuration: Double,
)
Parameters
frameStartTime
The time at which to start the specified animations. This value must be in the range 0 to 1, where 0 represents the start of the overall animation and 1 represents the end of the overall animation. For example, for an animation that is two seconds in duration, specifying a start time of 0.5 causes the animations to begin executing one second after the start of the overall animation.
frameDuration
The length of time over which to animate to the specified value. This value must be in the range 0 to 1 and indicates the amount of time relative to the overall animation length. If you specify a value of 0, any properties you set in the animations block update immediately at the specified start time. If you specify a nonzero value, the properties animate over that amount of time. For example, for an animation that is two seconds in duration, specifying a duration of 0.5 results in an animation duration of one second.
animations
A block object containing the animations you want to perform. This is where you programmatically change any animatable properties of the views in your view hierarchy. This block takes no parameters and has no return value. This parameter must not be nil.
Discussion
To animate view properties during a keyframe animation, call this method from within the animation block you pass to the animateKeyframes(withDuration:delay:options:animations:completion:) method. To animate between different values, or to tweak the timing of your view property animations, you can call this method multiple times within a block.
The view properties you change in the animations block animate over the timespan you specify in frameDuration parameter. The properties do not begin animating until the time you specify in the frameStartTime parameter. After the frame start time, the animation executes over its specified duration or until interrupted by another animation.
See Also
Animating views
Animates changes to one or more views using a spring animation with the specified duration, bounce, initial velocity, delay, options, and completion handler.
Animate changes to one or more views using the specified duration, delay, options, and completion handler.
Animate changes to one or more views using the specified duration and completion handler.
Animate changes to one or more views using the specified duration.
Creates a transition animation for the specified container view.
Creates a transition animation between the specified views using the given parameters.
Creates an animation block object that can be used to set up keyframe-based animations for the current view.
Performs a specified system-provided animation on one or more views, along with optional parallel animations that you define.
Performs a view animation using a timing curve corresponding to the motion of a physical spring.
Disables a view transition animation.
Repeats the specified animations a specific number of times, optionally running the animation forward and backward.
https://developer.apple.com/documentation/uikit/uiview/animate(withduration:delay:usingspringwithdamping:initialspringvelocity:options:animations:completion:)
#app-main)
- UIKit
- UIView
- animate(withDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:)
Type Method
animate(withDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:)
Performs a view animation using a timing curve corresponding to the motion of a physical spring.
tvOS
@MainActor class func animate( withDuration duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat, options: UIView.AnimationOptions = [],
)
Parameters
duration
The total duration of the animations, measured in seconds. If you specify a negative value or 0, the changes are made without animating them.
delay
The amount of time (measured in seconds) to wait before beginning the animations. Specify a value of 0 to begin the animations immediately.
dampingRatio
The damping ratio for the spring animation as it approaches its quiescent state.
To smoothly decelerate the animation without oscillation, use a value of 1. Employ a damping ratio closer to zero to increase oscillation.
velocity
The initial spring velocity. For smooth start to the animation, match this value to the view’s velocity as it was prior to attachment.
A value of 1 corresponds to the total animation distance traversed in one second. For example, if the total animation distance is 200 points and you want the start of the animation to match a view velocity of 100 pt/s, use a value of 0.5.
options
A mask of options indicating how you want to perform the animations. For a list of valid constants, see UIView.AnimationOptions.
animations
A block object containing the changes to commit to the views. This is where you programmatically change any animatable properties of the views in your view hierarchy. This block takes no parameters and has no return value. This parameter must not be NULL.
completion
A block object to be executed when the animation sequence ends. This block has no return value and takes a single Boolean argument that indicates whether or not the animations actually finished before the completion handler was called. If the duration of the animation is 0, this block is performed at the beginning of the next run loop cycle. This parameter may be NULL.
See Also
Animating views
Animates changes to one or more views using a spring animation with the specified duration, bounce, initial velocity, delay, options, and completion handler.
Animate changes to one or more views using the specified duration, delay, options, and completion handler.
Animate changes to one or more views using the specified duration and completion handler.
Animate changes to one or more views using the specified duration.
Creates a transition animation for the specified container view.
Creates a transition animation between the specified views using the given parameters.
Creates an animation block object that can be used to set up keyframe-based animations for the current view.
Specifies the timing and animation values for a single frame of a keyframe animation.
Performs a specified system-provided animation on one or more views, along with optional parallel animations that you define.
Disables a view transition animation.
Repeats the specified animations a specific number of times, optionally running the animation forward and backward.
https://developer.apple.com/documentation/uikit/uiview/performwithoutanimation(_:)
#app-main)
- UIKit
- UIView
- performWithoutAnimation(_:)
Type Method
performWithoutAnimation(_:)
Disables a view transition animation.
tvOS
@MainActor
Parameters
actionsWithoutAnimation
The view transition code that you want to perform without animation.
See Also
Related Documentation
class var areAnimationsEnabled: Bool
Returns a Boolean value indicating whether animations are enabled.
class func setAnimationsEnabled(Bool)
Sets whether animations are enabled.
Animating views
Animates changes to one or more views using a spring animation with the specified duration, bounce, initial velocity, delay, options, and completion handler.
Animate changes to one or more views using the specified duration, delay, options, and completion handler.
Animate changes to one or more views using the specified duration and completion handler.
Animate changes to one or more views using the specified duration.
Creates a transition animation for the specified container view.
Creates a transition animation between the specified views using the given parameters.
Creates an animation block object that can be used to set up keyframe-based animations for the current view.
Specifies the timing and animation values for a single frame of a keyframe animation.
Performs a specified system-provided animation on one or more views, along with optional parallel animations that you define.
Performs a view animation using a timing curve corresponding to the motion of a physical spring.
Repeats the specified animations a specific number of times, optionally running the animation forward and backward.
https://developer.apple.com/documentation/uikit/uiview/modifyanimations(withrepeatcount:autoreverses:animations:)
#app-main)
- UIKit
- UIView
- modifyAnimations(withRepeatCount:autoreverses:animations:)
Type Method
modifyAnimations(withRepeatCount:autoreverses:animations:)
Repeats the specified animations a specific number of times, optionally running the animation forward and backward.
@MainActor class func modifyAnimations( withRepeatCount count: CGFloat, autoreverses: Bool,
)
Parameters
count
The number of times to repeat the animations.
autoreverses
A Boolean value that indicates whether the animations run forward and backward.
animations
The animations to perform.
Discussion
You must call this method from within an enclosing animation block. The inverse nesting, calling animate(withDuration:animations:) from inside the modifyAnimations(withRepeatCount:autoreverses:animations:) block, doesn’t work.
UIView.animate(withDuration: 1.0) { UIView.modifyAnimations(withRepeatCount: 2, autoreverses: true) { // Set view properties. } }
See Also
Animating views
Animates changes to one or more views using a spring animation with the specified duration, bounce, initial velocity, delay, options, and completion handler.
Animate changes to one or more views using the specified duration, delay, options, and completion handler.
Animate changes to one or more views using the specified duration and completion handler.
Animate changes to one or more views using the specified duration.
Creates a transition animation for the specified container view.
Creates a transition animation between the specified views using the given parameters.
Creates an animation block object that can be used to set up keyframe-based animations for the current view.
Specifies the timing and animation values for a single frame of a keyframe animation.
Performs a specified system-provided animation on one or more views, along with optional parallel animations that you define.
Performs a view animation using a timing curve corresponding to the motion of a physical spring.
Disables a view transition animation.
https://developer.apple.com/documentation/uikit/uiview/animationcurve
- UIKit
- UIView
- UIView.AnimationCurve
Enumeration
UIView.AnimationCurve
Specifies the supported animation curves.
iOSiPadOSMac CatalysttvOSvisionOS
enum AnimationCurve
Topics
Constants
case easeInOut
An ease-in ease-out curve causes the animation to begin slowly, accelerate through the middle of its duration, and then slow again before completing. This is the default curve for most animations.
case easeIn
An ease-in curve causes the animation to begin slowly, and then speed up as it progresses.
case easeOut
An ease-out curve causes the animation to begin quickly, and then slow down as it completes.
case linear
A linear animation curve causes an animation to occur evenly over its duration.
Initializers
init?(rawValue: Int)
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Constants
struct AnimationOptions
Options for animating views using block objects.
enum AnimationTransition
Animation transition options for use in an animation block object.
enum SystemAnimation
Option to remove the views from the hierarchy when animation is complete.
struct KeyframeAnimationOptions
Options for configuring keyframe-based animations.
enum Axis
Keys that specify a horizontal or vertical layout constraint between objects.
enum TintAdjustmentMode
The tint adjustment mode for the view.
class let layoutFittingCompressedSize: CGSize
The option to use the smallest possible size.
class let layoutFittingExpandedSize: CGSize
The option to use the largest possible size.
class let noIntrinsicMetric: CGFloat
The absence of an intrinsic metric for a given numeric view property.
struct AutoresizingMask
Options for automatic view resizing.
enum UISemanticContentAttribute
A semantic description of the view’s contents, used to determine whether the view should be flipped when switching between left-to-right and right-to-left layouts.
https://developer.apple.com/documentation/uikit/uiview/animationoptions
https://developer.apple.com/documentation/uikit/uiview/animationtransition
https://developer.apple.com/documentation/uikit/uiview/systemanimation
- UIKit
- UIView
- UIView.SystemAnimation
Enumeration
UIView.SystemAnimation
Option to remove the views from the hierarchy when animation is complete.
tvOS
enum SystemAnimation
Topics
Constants
case delete
Option to remove views from the view hierarchy when animation is complete.
Initializers
init?(rawValue: UInt)
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Constants
enum AnimationCurve
Specifies the supported animation curves.
struct AnimationOptions
Options for animating views using block objects.
enum AnimationTransition
Animation transition options for use in an animation block object.
struct KeyframeAnimationOptions
Options for configuring keyframe-based animations.
enum Axis
Keys that specify a horizontal or vertical layout constraint between objects.
enum TintAdjustmentMode
The tint adjustment mode for the view.
class let layoutFittingCompressedSize: CGSize
The option to use the smallest possible size.
class let layoutFittingExpandedSize: CGSize
The option to use the largest possible size.
class let noIntrinsicMetric: CGFloat
The absence of an intrinsic metric for a given numeric view property.
struct AutoresizingMask
Options for automatic view resizing.
enum UISemanticContentAttribute
A semantic description of the view’s contents, used to determine whether the view should be flipped when switching between left-to-right and right-to-left layouts.
https://developer.apple.com/documentation/uikit/uiview/keyframeanimationoptions
- UIKit
- UIView
- UIView.KeyframeAnimationOptions
Structure
UIView.KeyframeAnimationOptions
Options for configuring keyframe-based animations.
tvOS
struct KeyframeAnimationOptions
Overview
Use these options with the animateKeyframes(withDuration:delay:options:animations:completion:) method.
Topics
Constants
static var layoutSubviews: UIView.KeyframeAnimationOptions
The option to lay out subviews at commit time so that they’re animated along with their parent.
static var allowUserInteraction: UIView.KeyframeAnimationOptions
The option that allows a person to interact with views while they’re being animated.
static var beginFromCurrentState: UIView.KeyframeAnimationOptions
The option to start an animation from the current setting associated with an already in-flight animation.
static var `repeat`: UIView.KeyframeAnimationOptions
The option to repeat an animation indefinitely.
static var autoreverse: UIView.KeyframeAnimationOptions
The option to run an animation backwards and forwards.
static var overrideInheritedDuration: UIView.KeyframeAnimationOptions
The option to force an animation to use the original duration value specified when the animation was submitted.
static var overrideInheritedOptions: UIView.KeyframeAnimationOptions
The option to not inherit the animation type or any options.
static var calculationModeLinear: UIView.KeyframeAnimationOptions
The option to use a simple linear calculation when interpolating between keyframe values.
static var calculationModeDiscrete: UIView.KeyframeAnimationOptions
The option to not interpolate between keyframe values, but rather to jump directly to each new keyframe value.
static var calculationModePaced: UIView.KeyframeAnimationOptions
The option to compute intermediate keyframe values using a simple pacing algorithm.
static var calculationModeCubic: UIView.KeyframeAnimationOptions
The option to compute intermediate frames using a default Catmull-Rom spline that passes through the keyframe values.
static var calculationModeCubicPaced: UIView.KeyframeAnimationOptions
The option to compute intermediate frames using the cubic scheme while ignoring the timing properties of the animation.
Initializers
init(rawValue: UInt)
Creates keyframe animation options with the specified raw value.
Relationships
Conforms To
BitwiseCopyableEquatableExpressibleByArrayLiteralOptionSetRawRepresentableSendableSendableMetatypeSetAlgebra
See Also
Constants
enum AnimationCurve
Specifies the supported animation curves.
struct AnimationOptions
Options for animating views using block objects.
enum AnimationTransition
Animation transition options for use in an animation block object.
enum SystemAnimation
Option to remove the views from the hierarchy when animation is complete.
enum Axis
Keys that specify a horizontal or vertical layout constraint between objects.
enum TintAdjustmentMode
The tint adjustment mode for the view.
class let layoutFittingCompressedSize: CGSize
The option to use the smallest possible size.
class let layoutFittingExpandedSize: CGSize
The option to use the largest possible size.
class let noIntrinsicMetric: CGFloat
The absence of an intrinsic metric for a given numeric view property.
struct AutoresizingMask
Options for automatic view resizing.
enum UISemanticContentAttribute
A semantic description of the view’s contents, used to determine whether the view should be flipped when switching between left-to-right and right-to-left layouts.
https://developer.apple.com/documentation/uikit/nslayoutconstraint/axis
- UIKit
- NSLayoutConstraint
- NSLayoutConstraint.Axis
Enumeration
NSLayoutConstraint.Axis
Keys that specify a horizontal or vertical layout constraint between objects.
iOSiPadOSMac CatalysttvOSvisionOS
enum Axis
Topics
Constants
case horizontal
The constraint applied when laying out the horizontal relationship between objects.
case vertical
The constraint applied when laying out the vertical relationship between objects.
Initializers
init?(rawValue: Int)
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Constants
enum Relation
The relation between the first attribute and the modified second attribute in a constraint.
enum Attribute
The part of the object’s visual representation that should be used to get the value for the constraint.
struct FormatOptions
A bit mask that specifies both a part of an interface element to align and a direction for the alignment between two interface elements.
enum Orientation
The layout constraint orientation, either horizontal or vertical, that the constraint uses to enforce layout between objects.
struct NSEdgeInsets
A description of the distance between the edges of two rectangles.
var NSLAYOUTCONSTRAINT_H: Int32
https://developer.apple.com/documentation/uikit/uiview/tintadjustmentmode-swift.enum
- UIKit
- UIView
- UIView.TintAdjustmentMode
Enumeration
UIView.TintAdjustmentMode
The tint adjustment mode for the view.
tvOS
enum TintAdjustmentMode
Topics
Constants
case automatic
The tint adjustment mode of the view is the same as its superview’s tint adjustment mode (or UIViewTintAdjustmentModeNormal if the view has no superview).
case normal
The view’s tint color property returns the completely unmodified tint color of the view.
case dimmed
The view’s tint color property returns a desaturated, dimmed version of the view’s original tint color.
Initializers
init?(rawValue: Int)
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Constants
enum AnimationCurve
Specifies the supported animation curves.
struct AnimationOptions
Options for animating views using block objects.
enum AnimationTransition
Animation transition options for use in an animation block object.
enum SystemAnimation
Option to remove the views from the hierarchy when animation is complete.
struct KeyframeAnimationOptions
Options for configuring keyframe-based animations.
enum Axis
Keys that specify a horizontal or vertical layout constraint between objects.
class let layoutFittingCompressedSize: CGSize
The option to use the smallest possible size.
class let layoutFittingExpandedSize: CGSize
The option to use the largest possible size.
class let noIntrinsicMetric: CGFloat
The absence of an intrinsic metric for a given numeric view property.
struct AutoresizingMask
Options for automatic view resizing.
enum UISemanticContentAttribute
A semantic description of the view’s contents, used to determine whether the view should be flipped when switching between left-to-right and right-to-left layouts.
https://developer.apple.com/documentation/uikit/uiview/layoutfittingcompressedsize
https://developer.apple.com/documentation/uikit/uiview/layoutfittingexpandedsize
- UIKit
- UIView
- layoutFittingExpandedSize
Type Property
layoutFittingExpandedSize
The option to use the largest possible size.
tvOS
class let layoutFittingExpandedSize: CGSize
See Also
Constants
enum AnimationCurve
Specifies the supported animation curves.
struct AnimationOptions
Options for animating views using block objects.
enum AnimationTransition
Animation transition options for use in an animation block object.
enum SystemAnimation
Option to remove the views from the hierarchy when animation is complete.
struct KeyframeAnimationOptions
Options for configuring keyframe-based animations.
enum Axis
Keys that specify a horizontal or vertical layout constraint between objects.
enum TintAdjustmentMode
The tint adjustment mode for the view.
class let layoutFittingCompressedSize: CGSize
The option to use the smallest possible size.
class let noIntrinsicMetric: CGFloat
The absence of an intrinsic metric for a given numeric view property.
struct AutoresizingMask
Options for automatic view resizing.
enum UISemanticContentAttribute
A semantic description of the view’s contents, used to determine whether the view should be flipped when switching between left-to-right and right-to-left layouts.
https://developer.apple.com/documentation/uikit/uiview/nointrinsicmetric
https://developer.apple.com/documentation/uikit/uiview/autoresizingmask-swift.struct
https://developer.apple.com/documentation/uikit/uisemanticcontentattribute
https://developer.apple.com/documentation/uikit/uiview-deprecated-symbols
https://developer.apple.com/documentation/uikit/uiview/init()
#app-main)
- UIKit
- UIView
- init()
Initializer
init()
@MainActor convenience init()
https://developer.apple.com/documentation/uikit/uiview/setneedsupdateproperties()
https://developer.apple.com/documentation/uikit/uiview/updateproperties()
https://developer.apple.com/documentation/uikit/uiview/updatepropertiesifneeded()
https://developer.apple.com/documentation/uikit/uiview/animate(_:changes:completion:)
#app-main)
- UIKit
- UIView
- animate(_:changes:completion:)
Type Method
animate(_:changes:completion:)
Mac Catalyst
@MainActor @preconcurrency static func animate( _ animation: Animation,
)
https://developer.apple.com/documentation/uikit/uiview/invalidations
- UIKit
- UIView
- UIView.Invalidations
Enumeration
UIView.Invalidations
Changes that cause an aspect of a view to be invalid and require an update.
Mac CatalystvisionOSSwift 5.1+
enum Invalidations
Topics
Invalidation types
struct Configuration
A change that invalidates a view’s configuration.
struct Constraints
A change that invalidates a view’s constraints.
struct Display
A change that requires the system to redraw a view’s content.
struct IntrinsicContentSize
A change that invalidates a view’s intrinsic size.
struct Layout
A change that invalidates the layout of the containing view’s subviews.
struct Tuple
A change that invalidates a combination of factors covered by the other invalidation types.
Structures
struct Properties
See Also
Invalidating the view
func invalidate(view: UIView)
Indicates to the system that an aspect of a view is invalid and triggers the necessary update.
Required
https://developer.apple.com/documentation/uikit/uibackgroundextensionview
- UIKit
- UIBackgroundExtensionView Beta
Class
UIBackgroundExtensionView
A view that extends content to fill its own bounds.
@MainActor class UIBackgroundExtensionView
Overview
A background extension view can be laid out to extend outside the safe area, such as under a sidebar or an inspector. By default, the view lays out its content to stay within the safe area, and uses modifications of the content along the edges to fill the container view.
Topics
Instance Properties
var automaticallyPlacesContentView: Bool
Controls the automatic safe area placement of the contentView within the container.
var contentView: UIView?
The content view to extend to fill the UIBackgroundExtensionView.
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Interacting with adjacent views
class UIScrollEdgeElementContainerInteraction
Add this interaction to a container view of views that overlay the edge of a scroll view. Any descendants of this view that should affect the shape of the edge effect, such as labels, images, glass views, and controls, will automatically do so.
Beta
Beta Software
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
Learn more about using Apple's beta software
https://developer.apple.com/documentation/uikit/uicollectionreusableview
- UIKit
- UICollectionReusableView
Class
UICollectionReusableView
A view that defines the behavior for all cells and supplementary views presented by a collection view.
tvOS
@MainActor class UICollectionReusableView
Overview
Reusable views are so named because the collection view places them on a reuse queue rather than deleting them when they’re scrolled out of the visible bounds. Such a view can then be retrieved and repurposed for a different set of content.
Subclassing notes
This class is intended to be subclassed. Most methods defined by this class have minimal or no implementations. You aren’t required to override any of the methods but can do so in cases where you want to respond to changes in the view’s usage or layout.
Topics
Reusing cells
var reuseIdentifier: String?
A string that identifies the purpose of the view.
func prepareForReuse()
Performs any clean up necessary to prepare the view for use again.
Managing layout changes
Gives the cell a chance to modify the attributes provided by the layout object.
func apply(UICollectionViewLayoutAttributes)
Applies the specified layout attributes to the view.
func willTransition(from: UICollectionViewLayout, to: UICollectionViewLayout)
Tells your view that the layout object of the collection view is about to change.
func didTransition(from: UICollectionViewLayout, to: UICollectionViewLayout)
Tells your view that the layout object of the collection view changed.
Relationships
Inherits From
UIView
Inherited By
UICollectionViewCell
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Cells
class UICollectionViewCell
A single data item when that item is within the collection view’s visible bounds.
class UICollectionViewListCell
A collection view cell that provides list features and default styling.
https://developer.apple.com/documentation/uikit/uiinputview
- UIKit
- UIInputView
Class
UIInputView
An object that displays and manages custom input for a view when that view becomes the first responder.
tvOS
@MainActor class UIInputView
Overview
The UIInputView class is designed to match the appearance of the standard system keyboard when used as an input view with a responder. When defining your own custom input views or input accessory views, you can use a UIInputView object as the root view and add any subviews you want to create your input view. The input view and its subviews receive tinting and blur effects based on the options you specify at initialization time.
Topics
Initializing an input view
init(frame: CGRect, inputViewStyle: UIInputView.Style)
Initializes and returns an input view using the specified style information.
init?(coder: NSCoder)
Creates an input view from data in an unarchiver.
Getting the input style
var inputViewStyle: UIInputView.Style
The style for the content of the view.
enum Style
Constants that indicate the appearance changes for an input view.
Sizing the input view
var allowsSelfSizing: Bool
A Boolean value that indicates whether the input view is responsible for its own size.
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Custom keyboards
Add an extension to your Xcode project to provide systemwide customized text input.
class UIInputViewController
The primary view controller for a custom keyboard app extension.
class UILexicon
A read-only array of term pairs, each in a lexicon entry object, for a custom keyboard.
class UILexiconEntry
A read-only term pair, available within a lexicon object, for a custom keyboard.
protocol UITextDocumentProxy
An object that provides textual context to a custom keyboard.
https://developer.apple.com/documentation/uikit/uilistcontentview
https://developer.apple.com/documentation/uikit/uipopoverbackgroundview
- UIKit
- UIPopoverBackgroundView
Class
UIPopoverBackgroundView
The background appearance for a popover.
tvOS
@MainActor class UIPopoverBackgroundView
Overview
This class must be subclassed before it can be used. The implementation of your subclass is responsible for providing the border decoration and arrow for the popover. Subclasses must override all declared properties and methods to provide information about where to lay out the corresponding popover content and arrow. Subclasses must also provide implementations for all methods of the UIPopoverBackgroundViewMethods protocol.
Subclassing notes
Your subclass is responsible for providing the background visual styling of the popover, which includes the arrow and appropriately styled border. The popover controller places the actual popover content on top of your background view to finish the popover’s presentation.
The background contents of your view should be based on stretchable images. Because the popover is animated into place (and may require animated transitions), using images is the only way to ensure that the animations are smooth and not jittery. By creating images that can be stretched at appropriate places, your popover can still be resized and adjusted as needed. You can then incorporate those images using UIImageView subviews or Core Animation layers. When the size of the popover changes (perhaps to accommodate the keyboard), all you have to do is adjust the frame rectangles of your embedded image views.
In addition to providing the background content, your subclass must implement the arrowOffset and arrowDirection properties and the methods in the UIPopoverBackgroundViewMethods protocol. The popover controller uses these methods and properties to get and set information related to your background view. The protocol methods are called once and the values you return should never change. However, the values in the arrowOffset and arrowDirection properties can change while your popover is on the screen, so your setter methods should call setNeedsLayout() when that happens to update the background image views or layers.
To create a stretchable image, use the resizableImage(withCapInsets:) method of UIImage.
Topics
Accessing the arrow metrics
var arrowOffset: CGFloat
The distance (measured in points) from the center of the view to the center line of the arrow.
var arrowDirection: UIPopoverArrowDirection
The direction in which the popover arrow is pointing.
Controlling the popover appearance
class var wantsDefaultContentAppearance: Bool
Determines whether the default content appearance should be used for the popover.
Deprecated
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverBackgroundViewMethodsUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Popovers
Displaying transient content in a popover
Show a temporary interface on top of your app’s content on iPad.
class UIPopoverPresentationController
An object that manages the display of content in a popover.
protocol UIPopoverBackgroundViewMethods
A set of methods that popover background view subclasses must implement.
https://developer.apple.com/documentation/uikit/uistandardtextcursorview
- UIKit
- UIStandardTextCursorView
Class
UIStandardTextCursorView
A view that draws the standard system insertion point in a piece of text.
@MainActor class UIStandardTextCursorView
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITextCursorViewUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Custom text selection
Adopting system selection UI in custom text views
Incorporate the system text-selection experience into your custom text UI in UIKit.
class UITextSelectionDisplayInteraction
An object that provides the system UI for displaying text selection.
protocol UITextSelectionHighlightView
An interface you use to provide a custom highlight UI behind the selected text.
protocol UITextSelectionHandleView
An interface you use to draw custom the selection handles for ranges of text.
protocol UITextCursorView
An interface you use to draw the insertion point in a piece of text.
class UITextCursorDropPositionAnimator
class UITextLoupeSession
An object that manages the presentation of the system magnifier at the location you specify.
https://developer.apple.com/documentation/uikit/uitableviewcell
- UIKit
- UITableViewCell
Class
UITableViewCell
The visual representation of a single row in a table view.
tvOS
@MainActor class UITableViewCell
Mentioned in
Filling a table with data
Configuring the cells for your table
Adding user-focusable elements to a tvOS app
Overview
A UITableViewCell object is a specialized type of view that manages the content of a single table row. You use cells primarily to organize and present your app’s custom content, but UITableViewCell provides some specific customizations to support table-related behaviors, including:
-
Applying a selection or highlight color to the cell
-
Adding standard accessory views, such as a detail or disclosure control
-
Putting the cell into an editable state
-
Indenting the cell’s content to create a visual hierarchy in your table
Your app’s content occupies most of the cell’s bounds, but the cell may adjust that space to make room for other content. Cells display accessory views on the trailing edge of their content area. When you put your table into edit mode, the cell adds a delete control to the leading edge of its content area, and optionally swaps out an accessory view for a reorder control.
Every table view must have at least one type of cell for displaying content, and tables may have multiple cell types to display different types of content. Your table’s data source object handles the creation and configuration of cells immediately before they appear onscreen. For information about how to create your table’s cells, see Filling a table with data.
Configure your cell’s content
Configure the content and layout of your cells in your storyboard file. Tables have one cell type by default, but you can add more by changing the value in the table’s Prototype Cells attribute. In addition to configuring the cell’s content, make sure you configure the following attributes:
-
Identifier. Use this identifier (also known as a reuse identifier) to create the cell.
-
Style. Choose one of the standard types or define a custom cell.
-
Class. Specify a
UITableViewCellsubclass with your custom behavior.
To configure the content and appearance of your cell, you can set its contentConfiguration and backgroundConfiguration.
Topics
Creating a table view cell
init(style: UITableViewCell.CellStyle, reuseIdentifier: String?)
Initializes a table cell with a style and a reuse identifier and returns it to the caller.
enum CellStyle
An enumeration for the various styles of cells.
init?(coder: NSCoder)
Creates a table view from data in an unarchiver.
Reusing cells
var reuseIdentifier: String?
A string for identifying a reusable cell.
func prepareForReuse()
Prepares a reusable cell for reuse by the table view’s delegate.
Configuring the background
Retrieves a background configuration with system default values.
var backgroundConfiguration: UIBackgroundConfiguration?
The current background configuration of the cell.
var automaticallyUpdatesBackgroundConfiguration: Bool
A Boolean value that determines whether the cell automatically updates its background configuration when its state changes.
var backgroundView: UIView?
The view to use as the background of the cell.
var selectedBackgroundView: UIView?
The view to use as the background for a selected cell.
var multipleSelectionBackgroundView: UIView?
The background view to use for a selected cell when the table view allows multiple row selections.
Managing the content
Retrieves a default list content configuration for the cell’s style.
var contentConfiguration: (any UIContentConfiguration)?
The current content configuration of the cell.
var automaticallyUpdatesContentConfiguration: Bool
A Boolean value that determines whether the cell automatically updates its content configuration when its state changes.
var contentView: UIView
The content view of the cell object.
Managing the state
var configurationState: UICellConfigurationState
The current configuration state of the cell.
func setNeedsUpdateConfiguration()
Informs the cell to update its configuration for its current state.
func updateConfiguration(using: UICellConfigurationState)
Updates the cell’s configuration using the current state.
var configurationUpdateHandler: UITableViewCell.ConfigurationUpdateHandler?
A block for handling updates to the cell’s configuration using the current state.
typealias ConfigurationUpdateHandler
The type of block for handling updates to the cell’s configuration using the current state.
Managing accessory views
var accessoryType: UITableViewCell.AccessoryType
The type of standard accessory view for the cell to use in the table view’s normal state.
var accessoryView: UIView?
The view to use on the right side of the cell, typically as a control, in the table view’s normal state.
var editingAccessoryType: UITableViewCell.AccessoryType
The type of standard accessory view for the cell to use in the table view’s editing state.
var editingAccessoryView: UIView?
The view to use on the right side of the cell, typically as a control, in the table view’s editing state.
enum AccessoryType
The type of standard accessory control used by a cell.
Managing cell selection and highlighting
var selectionStyle: UITableViewCell.SelectionStyle
The style of selection for a cell.
enum SelectionStyle
The style of selected cells.
var isSelected: Bool
A Boolean value that indicates whether the cell is selected.
func setSelected(Bool, animated: Bool)
Sets the selected state of the cell, optionally animating the transition between states.
var isHighlighted: Bool
A Boolean value that indicates whether the cell is highlighted.
func setHighlighted(Bool, animated: Bool)
Sets the highlighted state of the cell, optionally animating the transition between states.
Editing the cell
var isEditing: Bool
A Boolean value that indicates whether the cell is in an editable state.
func setEditing(Bool, animated: Bool)
Toggles the cell into and out of editing mode.
var editingStyle: UITableViewCell.EditingStyle
The editing style of the cell.
enum EditingStyle
The editing control used by a cell.
var showingDeleteConfirmation: Bool
A Boolean value that indicates whether the cell is currently showing the delete-confirmation button.
var showsReorderControl: Bool
A Boolean value that determines whether the cell shows the reordering control.
Dragging the row
var userInteractionEnabledWhileDragging: Bool
A Boolean value indicating whether users can interact with a cell while it is being dragged.
func dragStateDidChange(UITableViewCell.DragState)
Notifies the cell that its drag status changed.
enum DragState
Constants indicating the current state of a row involved in a drag operation.
Adjusting to state transitions
func willTransition(to: UITableViewCell.StateMask)
Notifies the cell that it’s about to transition to a new cell state.
func didTransition(to: UITableViewCell.StateMask)
Notifies the cell that it transitioned to a new cell state.
struct StateMask
Constants used to determine the new state of a cell as it transitions between states.
Managing content indentation
var indentationLevel: Int
The indentation level of the cell’s content.
var indentationWidth: CGFloat
The width for each level of indentation of a cell’s content.
var shouldIndentWhileEditing: Bool
A Boolean value that controls whether the cell background is indented when the table view is in editing mode.
var separatorInset: UIEdgeInsets
The inset values for the separator line drawn beneath the cell.
enum SeparatorStyle
The style for cells to use as separators.
Managing focus
var focusStyle: UITableViewCell.FocusStyle
The appearance of the cell when focused.
enum FocusStyle
The style of focused cells.
Deprecated
var textLabel: UILabel?
The label to use for the main textual content of the table cell.
Deprecated
var detailTextLabel: UILabel?
The secondary label of the table cell, if one exists.
var imageView: UIImageView?
The image view of the table cell.
Relationships
Inherits From
UIView
Conforms To
CALayerDelegateCVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSObjectProtocolNSTouchBarProviderSendableSendableMetatypeUIAccessibilityIdentificationUIActivityItemsConfigurationProvidingUIAppearanceUIAppearanceContainerUICoordinateSpaceUIDynamicItemUIFocusEnvironmentUIFocusItemUIFocusItemContainerUIGestureRecognizerDelegateUILargeContentViewerItemUIPasteConfigurationSupportingUIPopoverPresentationControllerSourceItemUIResponderStandardEditActionsUITraitChangeObservableUITraitEnvironmentUIUserActivityRestoring
See Also
Cells, headers, and footers
Specify the appearance and content of your table’s rows by defining one or more prototype cells in your storyboard.
Creating self-sizing table view cells
Create table view cells that support Dynamic Type and use system spacing constraints to adjust the spacing surrounding text labels.
Adding headers and footers to table sections
Differentiate groups of rows visually by adding header and footer views to your table view’s sections.
class UITableViewHeaderFooterView
A reusable view that you place at the top or bottom of a table section to display additional information for that section.
https://developer.apple.com/documentation/uikit/uitableviewheaderfooterview
https://developer.apple.com/documentation/uikit/uiaccessibilityidentification
- UIKit
- UIAccessibilityIdentification
Protocol
UIAccessibilityIdentification
Methods that associate a unique identifier with elements in your user interface.
iOSiPadOSMac CatalysttvOSvisionOS
protocol UIAccessibilityIdentification : NSObjectProtocol
Overview
You can use the identifiers you define in UI Automation scripts because the value of accessibilityIdentifier corresponds to the return value of the name method of UIAElement.
Topics
Accessing an element identifier
var accessibilityIdentifier: String?
A string that identifies the element.
Required
Relationships
Inherits From
NSObjectProtocol
Conforming Types
UIAccessibilityElementUIActionUIActionSheetUIActivityIndicatorViewUIAlertActionUIAlertViewUIBackgroundExtensionViewUIBarButtonItemUIBarItemUIButtonUICalendarViewUICollectionReusableViewUICollectionViewUICollectionViewCellUICollectionViewListCellUIColorWellUICommandUIContentUnavailableViewUIControlUIDatePickerUIDeferredMenuElementUIEventAttributionViewUIImageUIImageViewUIInputViewUIKeyCommandUILabelUIListContentViewUIMenuUIMenuElementUINavigationBarUIPageControlUIPasteControlUIPickerViewUIPopoverBackgroundViewUIProgressViewUIRefreshControlUIScrollViewUISearchBarUISearchTabUISearchTextFieldUISegmentedControlUISliderUIStackViewUIStandardTextCursorViewUIStepperUISwitchUITabUITabBarUITabBarItemUITabGroupUITableViewUITableViewCellUITableViewHeaderFooterViewUITextFieldUITextViewUIToolbarUIViewUIVisualEffectViewUIWebViewUIWindowUIWindowScene.ActivationAction
See Also
Behaviors
UIAccessibilityFocus
An informal protocol that provides a way to determine whether an assistive app, such as VoiceOver, has focus on an accessible element.
protocol UIAccessibilityReadingContent
Methods to implement for an object that represents content that users read, such as a book or an article.
protocol UIAccessibilityContentSizeCategoryImageAdjusting
Methods to determine when to adjust images for different content size categories.
struct UIAccessibilityTextualContext
Constants that describe a named context that helps identify and classify the type of text inside an element.
https://developer.apple.com/documentation/uikit/uiappearance
- UIKit
- UIAppearance
Protocol
UIAppearance
A collection of methods that gives you access to the appearance proxy for a class.
iOSiPadOSMac CatalysttvOSvisionOS
@MainActor protocol UIAppearance : NSObjectProtocol
Overview
You can customize the appearance of instances of a class by sending appearance-modification messages to the class’s appearance proxy.
There are two ways to customize appearance for objects: for all instances, and for instances contained within an instance of a container class.
To customize the appearance of all instances of a class, use appearance() to get the appearance proxy for the class. For example, to modify the bar background tint color for all instances of UINavigationBar:
UINavigationBar.appearance().barTintColor = navBarTintColor
To customize the appearances for instances of a class when contained within an instance of a container class, or instances in a hierarchy, use appearanceWhenContainedIn: to get the appearance proxy for the class. For example, to modify the appearance of bar buttons, based on the object that contains the navigation bar:
let navigationBarAppearance = UINavigationBar.appearance(whenContainedInInstancesOf: [UINavigationController.self]) navigationBarAppearance.setBackgroundImage(navBarBackgroundImage, for: .any, barMetrics: .default)
let barButtonNavigationBarAppearance = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.self]) barButtonNavigationBarAppearance.setBackgroundImage(barButtonNavBarImage, for: .normal, barMetrics: .default)
let barButtonToolbarAppearance = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UIToolbar.self]) barButtonToolbarAppearance.setBackgroundImage(barButtonToolbarImage, for: .normal, barMetrics: .default)
In any given view hierarchy, the outermost appearance proxy wins. Specificity (depth of the chain) is the tie-breaker. In other words, the containment statement in appearanceWhenContainedIn: is treated as a partial ordering. Given a concrete ordering (actual subview hierarchy), UIKit selects the partial ordering that’s the first unique match when reading the actual hierarchy from the window down.
You can further refine which instances of a class will have their appearance customized by specifying a trait collection. Use the appearance(for:) and appearanceForTraitCollection:whenContainedIn: methods to retrieve the proxy for a class with the specified trait collection.
To support appearance customization, a class must conform to the UIAppearanceContainer protocol and relevant accessor methods must be marked with UI_APPEARANCE_SELECTOR.
Topics
Working with the appearance proxy
Returns the appearance proxy for the receiver.
Required
Returns the appearance proxy for the receiver that has the passed trait collection.
Returns the appearance proxy for the object when it’s contained in the hierarchy the specified classes describe.
Returns the appearance proxy for the object when it’s contained in the hierarchy the specified classes describe and has the specified trait collection.
Relationships
Inherits From
NSObjectProtocol
Conforming Types
UIActionSheetUIActivityIndicatorViewUIAlertViewUIBackgroundExtensionViewUIBarButtonItemUIBarItemUIButtonUICalendarViewUICollectionReusableViewUICollectionViewUICollectionViewCellUICollectionViewListCellUIColorWellUIContentUnavailableViewUIControlUIDatePickerUIEventAttributionViewUIImageViewUIInputViewUILabelUIListContentViewUINavigationBarUIPageControlUIPasteControlUIPickerViewUIPopoverBackgroundViewUIProgressViewUIRefreshControlUIScrollViewUISearchBarUISearchTextFieldUISegmentedControlUISliderUIStackViewUIStandardTextCursorViewUIStepperUISwitchUITabBarUITabBarItemUITableViewUITableViewCellUITableViewHeaderFooterViewUITextFieldUITextViewUIToolbarUIViewUIVisualEffectViewUIWebViewUIWindow
See Also
Appearance proxies
protocol UIAppearanceContainer
A protocol that a class must adopt to allow appearance customization using the UIAppearance API.
https://developer.apple.com/documentation/uikit/uiappearancecontainer
https://developer.apple.com/documentation/uikit/uicoordinatespace
- UIKit
- UICoordinateSpace
Protocol
UICoordinateSpace
A set of methods for converting between different frames of reference on a screen.
iOSiPadOStvOSvisionOSwatchOS
@MainActor protocol UICoordinateSpace : NSObjectProtocol
Overview
The UIView class adopts this protocol so that you can convert easily between most coordinate spaces in your app. The UIScreen class includes the coordinateSpace and fixedCoordinateSpace properties, which give you access to the screen’s coordinate spaces. You can adopt this protocol in your own classes to convert between your custom coordinate spaces and the coordinate spaces of your app’s views and screens.
In iOS 8 and later, window and screen coordinate spaces aren’t fixed to a specific device orientation. Instead, window and screen coordinates change to match the app’s interface orientation, which typically (but not always) matches the current device orientation. (View controllers still determine which interface orientations the app supports.) Rotating the window and screen simplifies the interactions between views, windows, and the screen. In cases where you still need a fixed frame of reference — for example, because you need to store the location of a touch event or onscreen item persistently — you can use the methods of this protocol to convert coordinate values to the fixed coordinate space provided by the UIScreen object.
To convert a point from a view’s current coordinate space to the screen’s fixed coordinate space, use code similar to the following:
[myView convertPoint:point toCoordinateSpace:myView.window.screen.fixedCoordinateSpace];
When implementing the methods of this protocol, you must convert coordinate values to or from your local coordinate space. When performing such conversions, use the screen coordinate space as an intermediate coordinate space, converting to screen coordinates before converting to the target coordinate space. For example, when converting from your local coordinate space to the coordinate space of another view, convert your local coordinates to the screen coordinate space first and then convert those screen coordinates to the coordinate space of the view.
Topics
Getting the bounds rectangle
var bounds: CGRect
The bounds rectangle describing the item’s location and size in its own coordinate system.
Required
Converting between coordinate spaces
Converts a point from the coordinate space of the current object to the specified coordinate space.
Converts a point from the specified coordinate space to the coordinate space of the current object.
Converts a rectangle from the coordinate space of the current object to the specified coordinate space.
Converts a rectangle from the specified coordinate space to the coordinate space of the current object.
Relationships
Inherits From
NSObjectProtocol
Inherited By
UITextCursorViewUITextSelectionHandleViewUITextSelectionHighlightView
Conforming Types
UIActionSheetUIActivityIndicatorViewUIAlertViewUIBackgroundExtensionViewUIButtonUICalendarViewUICollectionReusableViewUICollectionViewUICollectionViewCellUICollectionViewListCellUIColorWellUIContentUnavailableViewUIControlUIDatePickerUIEventAttributionViewUIImageViewUIInputViewUILabelUIListContentViewUINavigationBarUIPageControlUIPasteControlUIPickerViewUIPopoverBackgroundViewUIProgressViewUIRefreshControlUIScrollViewUISearchBarUISearchTextFieldUISegmentedControlUISliderUIStackViewUIStandardTextCursorViewUIStepperUISwitchUITabBarUITableViewUITableViewCellUITableViewHeaderFooterViewUITextFieldUITextViewUIToolbarUIViewUIVisualEffectViewUIWebViewUIWindow
See Also
Windows
class UIWindow
The backdrop for your app’s user interface and the object that dispatches events to your views.
https://developer.apple.com/documentation/uikit/uidynamicitem
https://developer.apple.com/documentation/uikit/uifocusenvironment
- UIKit
- UIFocusEnvironment
Protocol
UIFocusEnvironment
A set of methods that define the focus behavior for a branch of the view hierarchy.
@MainActor protocol UIFocusEnvironment : NSObjectProtocol
Overview
The UIFocusEnvironment protocol provides a common interface for specifying and reacting to focus behavior throughout your app. Classes in UIKit that conform to this protocol include UIView, UIViewController, UIWindow, and UIPresentationController — in other words, classes that are either directly or indirectly in control of views on the screen.
Topics
Requesting focus update
func setNeedsFocusUpdate()
Submits a request to the focus engine for a focus update in this environment.
Required
func updateFocusIfNeeded()
Tells the focus engine to force a focus update immediately.
Validating focus movements
Returns a Boolean value indicating whether the focus engine should allow the focus update described by the specified context to occur.
Responding to focus updates
func didUpdateFocus(in: UIFocusUpdateContext, with: UIFocusAnimationCoordinator)
Called immediately after the system updates the focus to a new view.
Controlling user-generated focus movements
var preferredFocusEnvironments: [any UIFocusEnvironment]
An array of focus environments, ordered by priority, to which this environment prefers focus to be directed during a focus update.
var preferredFocusedView: UIView?
Specifies the view that should be focused if this environment is focused.
Deprecated
Getting the sound to play during updates
Using custom sounds for focus movement
Customize the sounds users hear when focus moves.
Asks the delegate for the identifier of the sound to play when the object gains focus.
struct UIFocusSoundIdentifier
An identifier for a focus-related sound.
Checking the ancestry of the environment
Returns a Boolean value that indicates whether the focus environment contains the specified environment.
var parentFocusEnvironment: (any UIFocusEnvironment)?
The parent focus environment for this environment.
var focusItemContainer: (any UIFocusItemContainer)?
The container for the child focus items in this focus environment.
Identifying the focus group
var focusGroupIdentifier: String?
The identifier of the focus group that the environment belongs to.
Relationships
Inherits From
NSObjectProtocol
Inherited By
UIFocusItem
Conforming Types
UIActionSheetUIActivityIndicatorViewUIActivityViewControllerUIAlertControllerUIAlertViewUIBackgroundExtensionViewUIButtonUICalendarViewUICloudSharingControllerUICollectionReusableViewUICollectionViewUICollectionViewCellUICollectionViewControllerUICollectionViewListCellUIColorPickerViewControllerUIColorWellUIContentUnavailableViewUIControlUIDatePickerUIDocumentBrowserViewControllerUIDocumentMenuViewControllerUIDocumentPickerExtensionViewControllerUIDocumentPickerViewControllerUIDocumentViewControllerUIEventAttributionViewUIFontPickerViewControllerUIImagePickerControllerUIImageViewUIInputViewUIInputViewControllerUILabelUIListContentViewUINavigationBarUINavigationControllerUIPageControlUIPageViewControllerUIPasteControlUIPickerViewUIPopoverBackgroundViewUIPopoverPresentationControllerUIPresentationControllerUIProgressViewUIReferenceLibraryViewControllerUIRefreshControlUIScrollViewUISearchBarUISearchContainerViewControllerUISearchControllerUISearchTextFieldUISegmentedControlUISheetPresentationControllerUISliderUISplitViewControllerUIStackViewUIStandardTextCursorViewUIStepperUISwitchUITabBarUITabBarControllerUITableViewUITableViewCellUITableViewControllerUITableViewHeaderFooterViewUITextFieldUITextFormattingViewControllerUITextViewUIToolbarUIVideoEditorControllerUIViewUIViewControllerUIVisualEffectViewUIWebViewUIWindow
See Also
Focus interactions
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
About focus interactions for Apple TV
Design and implement intuitive control schemes for menus and interactive user interface layouts.
Adding user-focusable elements to a tvOS app
Create intuitive and easily manipulated user-interactive controls for your tvOS app.
class UIFocusSystem
Queries and reevaluates the currently focused item.
class UIFocusUpdateContext
An object that provides information relevant to a specific focus update from one view to another.
protocol UIFocusItem
An object that can become focused.
class UIFocusMovementHint
Provides movement hint information for the focused item.
protocol UIFocusItemContainer
The container responsible for providing geometric context to focus items within a given focus environment.
protocol UIFocusItemScrollableContainer
A type of focus item container that supports automatic scrolling of focusable content.
struct UIFocusGroupPriority
The importance of an item within a focus group, used by the focus system to determine the group’s primary item.
https://developer.apple.com/documentation/uikit/uifocusitem
https://developer.apple.com/documentation/uikit/uifocusitemcontainer
https://developer.apple.com/documentation/uikit/uipopoverpresentationcontrollersourceitem
- UIKit
- UIPopoverPresentationControllerSourceItem
Protocol
UIPopoverPresentationControllerSourceItem
A type that can be an anchor for a popover presentation controller.
protocol UIPopoverPresentationControllerSourceItem : NSObjectProtocol
Topics
Relationships
Inherits From
NSObjectProtocol
Conforming Types
NSUIViewToolbarItemUIActionSheetUIActivityIndicatorViewUIAlertViewUIBackgroundExtensionViewUIBarButtonItemUIButtonUICalendarViewUICollectionReusableViewUICollectionViewUICollectionViewCellUICollectionViewListCellUIColorWellUIContentUnavailableViewUIControlUIDatePickerUIEventAttributionViewUIFocusGuideUIImageViewUIInputViewUIKeyboardLayoutGuideUILabelUILayoutGuideUIListContentViewUINavigationBarUIPageControlUIPasteControlUIPickerViewUIPopoverBackgroundViewUIProgressViewUIRefreshControlUIScrollViewUISearchBarUISearchTabUISearchTextFieldUISegmentedControlUISliderUIStackViewUIStandardTextCursorViewUIStepperUISwitchUITabUITabBarUITabBarItemUITabGroupUITableViewUITableViewCellUITableViewHeaderFooterViewUITextFieldUITextViewUIToolbarUITrackingLayoutGuideUIViewUIVisualEffectViewUIWebViewUIWindow
See Also
Specifying the popover’s anchor point
var sourceItem: (any UIPopoverPresentationControllerSourceItem)?
The item on which to anchor the popover.
var sourceView: UIView?
The view containing the anchor rectangle for the popover.
var sourceRect: CGRect
The area in the source view in which you anchor the popover.
var barButtonItem: UIBarButtonItem?
The bar button item on which to anchor the popover.
Deprecated
https://developer.apple.com/documentation/uikit/customizing-drawings)
https://developer.apple.com/documentation/uikit/implementing-a-multi-touch-app)
https://developer.apple.com/documentation/uikit/making-a-view-into-a-drag-source)
https://developer.apple.com/documentation/uikit/uiview/clipstobounds)
https://developer.apple.com/documentation/uikit/uiview/frame)
https://developer.apple.com/documentation/uikit/uiview/bounds)
https://developer.apple.com/documentation/uikit/uiview/addsubview(_:))
https://developer.apple.com/documentation/uikit/uiview/insertsubview(_:abovesubview:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/insertsubview(_:belowsubview:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/exchangesubview(at:withsubviewat:))
https://developer.apple.com/documentation/uikit/uiview/draw(_:))
https://developer.apple.com/documentation/uikit/uiview/setneedsdisplay())
https://developer.apple.com/documentation/uikit/uiview/setneedsdisplay(_:))
https://developer.apple.com/documentation/uikit/uiview/center)
https://developer.apple.com/documentation/uikit/uiview/transform)
https://developer.apple.com/documentation/uikit/uiview/alpha)
https://developer.apple.com/documentation/uikit/uiview/backgroundcolor)
https://developer.apple.com/documentation/uikit/uiviewpropertyanimator)
https://developer.apple.com/documentation/uikit/uiviewpropertyanimator).
https://developer.apple.com/documentation/uikit/uiview),
https://developer.apple.com/documentation/uikit/uiview/init(frame:))
https://developer.apple.com/documentation/uikit/uiview/layerclass)
https://developer.apple.com/documentation/uikit/uiview/draw(_:for:))
https://developer.apple.com/documentation/uikit/uiview/requiresconstraintbasedlayout)
https://developer.apple.com/documentation/uikit/uiview/updateconstraints())
https://developer.apple.com/documentation/uikit/uiview/alignmentrect(forframe:)),
https://developer.apple.com/documentation/uikit/uiview/frame(foralignmentrect:))
https://developer.apple.com/documentation/uikit/uiview/didaddsubview(_:)),
https://developer.apple.com/documentation/uikit/uiview/willremovesubview(_:))
https://developer.apple.com/documentation/uikit/uiview/willmove(tosuperview:)),
https://developer.apple.com/documentation/uikit/uiview/didmovetosuperview())
https://developer.apple.com/documentation/uikit/uiview/gesturerecognizershouldbegin(_:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiresponder/touchesbegan(_:with:)),
https://developer.apple.com/documentation/uikit/uiresponder/touchesmoved(_:with:)),
https://developer.apple.com/documentation/uikit/uiresponder/touchesended(_:with:)),
https://developer.apple.com/documentation/uikit/uiresponder/touchescancelled(_:with:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/addconstraint(_:))
https://developer.apple.com/documentation/uikit/uiview/autoresizingmask-swift.property)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/contentmode-swift.property)
https://developer.apple.com/documentation/uikit/uiview/ishidden)
https://developer.apple.com/documentation/uikit/uiview/init(coder:))
https://developer.apple.com/documentation/uikit/uiview/isopaque)
https://developer.apple.com/documentation/uikit/uiview/tintcolor)
https://developer.apple.com/documentation/uikit/uiview/tintadjustmentmode-swift.property)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/clearscontextbeforedrawing)
https://developer.apple.com/documentation/uikit/uiview/mask)
https://developer.apple.com/documentation/uikit/uiview/layer)
https://developer.apple.com/documentation/uikit/uiview/isuserinteractionenabled)
https://developer.apple.com/documentation/uikit/uiview/ismultipletouchenabled)
https://developer.apple.com/documentation/uikit/uiview/isexclusivetouch)
https://developer.apple.com/documentation/uikit/uiview/transform3d)
https://developer.apple.com/documentation/uikit/uiview/anchorpoint)
https://developer.apple.com/documentation/uikit/uiview/superview)
https://developer.apple.com/documentation/uikit/uiview/subviews)
https://developer.apple.com/documentation/uikit/uiview/window)
https://developer.apple.com/documentation/uikit/uiview/bringsubviewtofront(_:))
https://developer.apple.com/documentation/uikit/uiview/sendsubviewtoback(_:))
https://developer.apple.com/documentation/uikit/uiview/removefromsuperview())
https://developer.apple.com/documentation/uikit/uiview/insertsubview(_:at:))
https://developer.apple.com/documentation/uikit/uiview/isdescendant(of:))
https://developer.apple.com/documentation/uikit/uiview/didaddsubview(_:))
https://developer.apple.com/documentation/uikit/uiview/willmove(tosuperview:))
https://developer.apple.com/documentation/uikit/uiview/willmove(towindow:))
https://developer.apple.com/documentation/uikit/uiview/didmovetowindow())
https://developer.apple.com/documentation/uikit/uiview/updatetraitsifneeded())
https://developer.apple.com/documentation/uikit/uiview/traitoverrides-fd9z)
https://developer.apple.com/documentation/uikit/uitraitoverrides-swift.struct)
https://developer.apple.com/documentation/uikit/positioning-content-within-layout-margins)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/directionallayoutmargins)
https://developer.apple.com/documentation/uikit/uiview/layoutmargins)
https://developer.apple.com/documentation/uikit/uiview/preservessuperviewlayoutmargins)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/layoutmarginsdidchange())
https://developer.apple.com/documentation/uikit/positioning-content-relative-to-the-safe-area)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/safeareainsets)
https://developer.apple.com/documentation/uikit/uiview/safearealayoutguide)
https://developer.apple.com/documentation/uikit/uiview/safeareainsetsdidchange())
https://developer.apple.com/documentation/uikit/uiview/insetslayoutmarginsfromsafearea)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/constraints)
https://developer.apple.com/documentation/uikit/uiview/addconstraints(_:))
https://developer.apple.com/documentation/uikit/uiview/removeconstraint(_:))
https://developer.apple.com/documentation/uikit/uiview/removeconstraints(_:))
https://developer.apple.com/documentation/uikit/uiview/bottomanchor)
https://developer.apple.com/documentation/uikit/uiview/centerxanchor)
https://developer.apple.com/documentation/uikit/uiview/centeryanchor)
https://developer.apple.com/documentation/uikit/uiview/firstbaselineanchor)
https://developer.apple.com/documentation/uikit/uiview/heightanchor)
https://developer.apple.com/documentation/uikit/uiview/lastbaselineanchor)
https://developer.apple.com/documentation/uikit/uiview/leadinganchor)
https://developer.apple.com/documentation/uikit/uiview/leftanchor)
https://developer.apple.com/documentation/uikit/uiview/rightanchor)
https://developer.apple.com/documentation/uikit/uiview/topanchor)
https://developer.apple.com/documentation/uikit/uiview/trailinganchor)
https://developer.apple.com/documentation/uikit/uiview/widthanchor)
https://developer.apple.com/documentation/uikit/uiview/addlayoutguide(_:))
https://developer.apple.com/documentation/uikit/uiview/layoutguides)
https://developer.apple.com/documentation/uikit/uiview/layoutmarginsguide)
https://developer.apple.com/documentation/uikit/uiview/readablecontentguide)
https://developer.apple.com/documentation/uikit/uiview/removelayoutguide(_:))
https://developer.apple.com/documentation/uikit/uiview/systemlayoutsizefitting(_:))
https://developer.apple.com/documentation/uikit/uiview/systemlayoutsizefitting(_:withhorizontalfittingpriority:verticalfittingpriority:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/intrinsiccontentsize)
https://developer.apple.com/documentation/uikit/uiview/invalidateintrinsiccontentsize())
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/contentcompressionresistancepriority(for:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/setcontentcompressionresistancepriority(_:for:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/contenthuggingpriority(for:))
https://developer.apple.com/documentation/uikit/uiview/setcontenthuggingpriority(_:for:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/alignmentrect(forframe:))
https://developer.apple.com/documentation/uikit/uiview/alignmentrectinsets)
https://developer.apple.com/documentation/uikit/uiview/forfirstbaselinelayout)
https://developer.apple.com/documentation/uikit/uiview/forlastbaselinelayout)
https://developer.apple.com/documentation/uikit/uiview/needsupdateconstraints())
https://developer.apple.com/documentation/uikit/uiview/setneedsupdateconstraints())
https://developer.apple.com/documentation/uikit/uiview/updateconstraintsifneeded())
https://developer.apple.com/documentation/uikit/uiview/constraintsaffectinglayout(for:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/hasambiguouslayout)
https://developer.apple.com/documentation/uikit/uiview/exerciseambiguityinlayout())
https://developer.apple.com/documentation/uikit/uiview/contentmode-swift.enum)
https://developer.apple.com/documentation/uikit/uiview/sizethatfits(_:))
https://developer.apple.com/documentation/uikit/uiview/sizetofit())
https://developer.apple.com/documentation/uikit/uiview/autoresizessubviews)
https://developer.apple.com/documentation/uikit/uiview/layoutsubviews())
https://developer.apple.com/documentation/uikit/uiview/setneedslayout())
https://developer.apple.com/documentation/uikit/uiview/layoutifneeded())
https://developer.apple.com/documentation/uikit/uiview/translatesautoresizingmaskintoconstraints)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/layoutregion)
https://developer.apple.com/documentation/uikit/uiview/directionaledgeinsets(for:))
https://developer.apple.com/documentation/uikit/uiview/edgeinsets(for:))
https://developer.apple.com/documentation/uikit/uiview/layoutguide(for:))
https://developer.apple.com/documentation/uikit/uiview/overrideuserinterfacestyle)
https://developer.apple.com/documentation/uikit/uiview/semanticcontentattribute)
https://developer.apple.com/documentation/uikit/uiview/effectiveuserinterfacelayoutdirection)
https://developer.apple.com/documentation/uikit/uiview/userinterfacelayoutdirection(for:))
https://developer.apple.com/documentation/uikit/uiview/userinterfacelayoutdirection(for:relativeto:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/keyboardlayoutguide)
https://developer.apple.com/documentation/uikit/uiview/addinteraction(_:))
https://developer.apple.com/documentation/uikit/uiview/removeinteraction(_:))
https://developer.apple.com/documentation/uikit/uiview/interactions)
https://developer.apple.com/documentation/uikit/uiinteraction)
https://developer.apple.com/documentation/uikit/uiview/contentscalefactor)
https://developer.apple.com/documentation/uikit/uiview/tintcolordidchange())
https://developer.apple.com/documentation/uikit/uiview/invalidating)
https://developer.apple.com/documentation/uikit/uiviewinvalidating)
https://developer.apple.com/documentation/uikit/uiview/viewprintformatter())
https://developer.apple.com/documentation/uikit/uiview/addgesturerecognizer(_:))
https://developer.apple.com/documentation/uikit/uiview/removegesturerecognizer(_:))
https://developer.apple.com/documentation/uikit/uiview/gesturerecognizers)
https://developer.apple.com/documentation/uikit/uiview/canbecomefocused)
https://developer.apple.com/documentation/uikit/uiview/inheritedanimationduration)
https://developer.apple.com/documentation/uikit/uiview/isfocused)
https://developer.apple.com/documentation/uikit/uiview/focusgroupidentifier)
https://developer.apple.com/documentation/uikit/uiview/focuseffect)
https://developer.apple.com/documentation/uikit/uiview/focusgrouppriority)
https://developer.apple.com/documentation/uikit/uiview/addmotioneffect(_:))
https://developer.apple.com/documentation/uikit/uiview/motioneffects)
https://developer.apple.com/documentation/uikit/uiview/removemotioneffect(_:))
https://developer.apple.com/documentation/uikit/uiview/hoverstyle)
https://developer.apple.com/documentation/uikit/uihoverstyle)
https://developer.apple.com/documentation/uikit/uihovereffectlayer)
https://developer.apple.com/documentation/uikit/uiview/minimumcontentsizecategory)
https://developer.apple.com/documentation/uikit/uiview/maximumcontentsizecategory)
https://developer.apple.com/documentation/uikit/uiview/appliedcontentsizecategorylimitsdescription)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/restorationidentifier)
https://developer.apple.com/documentation/uikit/uiview/encoderestorablestate(with:))
https://developer.apple.com/documentation/uikit/uiview/decoderestorablestate(with:))
https://developer.apple.com/documentation/uikit/uiview/snapshotview(afterscreenupdates:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/resizablesnapshotview(from:afterscreenupdates:withcapinsets:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/drawhierarchy(in:afterscreenupdates:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/tag)
https://developer.apple.com/documentation/uikit/uiview/viewwithtag(_:))
https://developer.apple.com/documentation/uikit/uiview/convert(_:to:)-1xizt)
https://developer.apple.com/documentation/uikit/uiview/convert(_:from:)-8neo1)
https://developer.apple.com/documentation/uikit/uiview/convert(_:to:)-2kf3d)
https://developer.apple.com/documentation/uikit/uiview/convert(_:from:)-7irzk)
https://developer.apple.com/documentation/uikit/uiview/hittest(_:with:))
https://developer.apple.com/documentation/uikit/uiview/point(inside:with:))
https://developer.apple.com/documentation/uikit/uiview/endediting(_:))
https://developer.apple.com/documentation/uikit/uiview/accessibilityignoresinvertcolors)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/largecontentimage)
https://developer.apple.com/documentation/uikit/uiview/largecontentimageinsets)
https://developer.apple.com/documentation/uikit/uiview/largecontenttitle)
https://developer.apple.com/documentation/uikit/uiview/scaleslargecontentimage)
https://developer.apple.com/documentation/uikit/uiview/showslargecontentviewer)
https://developer.apple.com/documentation/uikit/uiview/animate(springduration:bounce:initialspringvelocity:delay:options:animations:completion:))
https://developer.apple.com/documentation/uikit/uiview/animate(withduration:delay:options:animations:completion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/animate(withduration:animations:completion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/animate(withduration:animations:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/transition(with:duration:options:animations:completion:))
https://developer.apple.com/documentation/uikit/uiview/transition(from:to:duration:options:completion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/animatekeyframes(withduration:delay:options:animations:completion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/addkeyframe(withrelativestarttime:relativeduration:animations:))
https://developer.apple.com/documentation/uikit/uiview/perform(_🔛options:animations:completion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/animate(withduration:delay:usingspringwithdamping:initialspringvelocity:options:animations:completion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/performwithoutanimation(_:))
https://developer.apple.com/documentation/uikit/uiview/modifyanimations(withrepeatcount:autoreverses:animations:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/animationcurve)
https://developer.apple.com/documentation/uikit/uiview/animationoptions)
https://developer.apple.com/documentation/uikit/uiview/animationtransition)
https://developer.apple.com/documentation/uikit/uiview/systemanimation)
https://developer.apple.com/documentation/uikit/uiview/keyframeanimationoptions)
https://developer.apple.com/documentation/uikit/nslayoutconstraint/axis)
https://developer.apple.com/documentation/uikit/uiview/tintadjustmentmode-swift.enum)
https://developer.apple.com/documentation/uikit/uiview/layoutfittingcompressedsize)
https://developer.apple.com/documentation/uikit/uiview/layoutfittingexpandedsize)
https://developer.apple.com/documentation/uikit/uiview/nointrinsicmetric)
https://developer.apple.com/documentation/uikit/uiview/autoresizingmask-swift.struct)
https://developer.apple.com/documentation/uikit/uisemanticcontentattribute)
https://developer.apple.com/documentation/uikit/uiview-deprecated-symbols)
https://developer.apple.com/documentation/uikit/uiview/init())
https://developer.apple.com/documentation/uikit/uiview/setneedsupdateproperties())
https://developer.apple.com/documentation/uikit/uiview/updateproperties())
https://developer.apple.com/documentation/uikit/uiview/updatepropertiesifneeded())
https://developer.apple.com/documentation/uikit/uiview/animate(_:changes:completion:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiview/invalidations)
https://developer.apple.com/documentation/uikit/uibackgroundextensionview)
https://developer.apple.com/documentation/uikit/uicollectionreusableview)
https://developer.apple.com/documentation/uikit/uiinputview)
https://developer.apple.com/documentation/uikit/uilistcontentview)
https://developer.apple.com/documentation/uikit/uipopoverbackgroundview)
https://developer.apple.com/documentation/uikit/uistandardtextcursorview)
https://developer.apple.com/documentation/uikit/uitableviewcell)
https://developer.apple.com/documentation/uikit/uitableviewheaderfooterview)
https://developer.apple.com/documentation/uikit/uiaccessibilityidentification)
https://developer.apple.com/documentation/uikit/uiappearance)
https://developer.apple.com/documentation/uikit/uiappearancecontainer)
https://developer.apple.com/documentation/uikit/uicoordinatespace)
https://developer.apple.com/documentation/uikit/uidynamicitem)
https://developer.apple.com/documentation/uikit/uifocusenvironment)
https://developer.apple.com/documentation/uikit/uifocusitem)
https://developer.apple.com/documentation/uikit/uifocusitemcontainer)
https://developer.apple.com/documentation/uikit/uipopoverpresentationcontrollersourceitem)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/String:%20Any
https://developer.apple.com/documentation/uikit/uiviewcontroller/viewdidload()
#app-main)
- UIKit
- UIViewController
- viewDidLoad()
Instance Method
viewDidLoad()
Called after the controller’s view is loaded into memory.
tvOS
@MainActor func viewDidLoad()
Mentioned in
Displaying and managing views with a view controller
Making a view into a drag source
Customizing a document-based app’s launch experience
Discussion
This method is called after the view controller has loaded its view hierarchy into memory. This method is called regardless of whether the view hierarchy was loaded from a nib file or created programmatically in the loadView() method. You usually override this method to perform additional initialization on views that were loaded from nib files.
See Also
Managing the view
var view: UIView!
The view that the controller manages.
var viewIfLoaded: UIView?
The view controller’s view, or nil if the view isn’t yet loaded.
var isViewLoaded: Bool
A Boolean value indicating whether the view is currently loaded into memory.
func loadView()
Creates the view that the controller manages.
func loadViewIfNeeded()
Loads the view controller’s view if it’s not loaded yet.
var title: String?
A localized string that represents the view this controller manages.
var preferredContentSize: CGSize
The preferred size for the view controller’s view.
https://developer.apple.com/documentation/uikit/uicolor
- UIKit
- UIColor
Class
UIColor
An object that stores color data and sometimes opacity.
tvOS
class UIColor
Mentioned in
Customizing drawings
Determining color values with color spaces
Understanding a drag item as a promise
Overview
Use color to customize your app’s appearance, communicate status, and help people visualize data. To learn more about using color in your apps, see Human Interface Guidelines.
UIColor provides a list of class properties that create adaptable and fixed colors such as blue, green, purple, and more. UIColor also offers properties to specify system-provided colors for UI elements such as labels, text, and buttons. You can create color objects by specifying color component values such as RGB, hue, and saturation. You can also create colors from other color objects and even create a pattern-based color from an image.
Topics
Getting existing colors
Choose colors for UI elements such as labels, text, backgrounds, and links.
Define standard color objects for specific shades, such as red, blue, green, black, white, and more.
Load colors from asset catalogs and create colors from raw component values.
Applying the color to the drawing environment
Create custom colors and patterns for drawing in your app.
func set()
Sets the color of subsequent stroke and fill operations to the color that the receiver represents.
func setFill()
Sets the color of subsequent fill operations to the color that the receiver represents.
func setStroke()
Sets the color of subsequent stroke operations to the color that the receiver represents.
Getting the color information
Change the system’s interpretation of a color value for display by selecting a color space.
var cgColor: CGColor
The Quartz color that corresponds to the color object.
var ciColor: CIColor
The Core Image color that corresponds to the color object.
Returns the components that form the color in the HSB color space.
Returns the components that form the color in the RGB color space.
Returns the grayscale components of the color.
var linearExposure: CGFloat
The linear brightness multiplier that was applied when generating this color. Colors created with an exposure by UIColor create CGColors that are tagged with a contentHeadroom value. While CGColors created without a contentHeadroom tag will return 0 from CGColorGetHeadroom, UIColors generated in a similar fashion return a linearExposure of 1.0.
Beta
var accessibilityName: String
A localized description of the color for accessibility attributes.
Resolving a dynamically generated color
Returns the version of the current color that results from the specified traits.
Working with color prominence
var prominence: UIColor.Prominence
Returns the version of the current color that results from applying the specified prominence.
enum Prominence
A type that indicates the prominence of a color in the interface.
Working with high dynamic range (HDR) colors
var standardDynamicRange: UIColor
Relationships
Inherits From
NSObject
Conforms To
CVarArgCopyableCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSCopyingNSItemProviderReadingNSItemProviderWritingNSObjectProtocolNSSecureCodingSendableSendableMetatype
https://developer.apple.com/documentation/uikit/displaying-a-preferences-window).
https://developer.apple.com/documentation/uikit/uiviewcontroller/viewdidload())
https://developer.apple.com/documentation/uikit/uicolor)
https://developer.apple.com/documentation/uikit/uiswitch/preferredstyle
- UIKit
- UISwitch
- preferredStyle
Instance Property
preferredStyle
The preferred display style for the switch.
@MainActor var preferredStyle: UISwitch.Style { get set }
Mentioned in
Displaying a checkbox in your Mac app built with Mac Catalyst
Choosing a user interface idiom for your Mac app
Discussion
Use this property to specify the display style that you prefer. If the style changes, the switch may generate a layout pass to update the display.
The default style is UISwitch.Style.automatic. For a list of styles, see UISwitch.Style.
See Also
Setting the display style
Present a switch control as a Mac-style checkbox when your app runs in the Mac user interface idiom.
var style: UISwitch.Style
The display style for the switch.
enum Style
Styles that determine the appearance of the switch.
var title: String?
The title displayed next to a checkbox-style switch.
https://developer.apple.com/documentation/uikit/uiswitch/style-swift.enum/automatic
- UIKit
- UISwitch
- UISwitch.Style
- UISwitch.Style.automatic
Case
UISwitch.Style.automatic
A style indicating that the system chooses the appearance of the switch according to the current user interface idiom.
case automatic
Mentioned in
Displaying a checkbox in your Mac app built with Mac Catalyst
Discussion
The system chooses the UISwitch.Style.checkbox style when the user interface idiom is UIUserInterfaceIdiom.mac; otherwise, it chooses the UISwitch.Style.sliding style.
See Also
Styles
case checkbox
A style indicating that the switch appears as a Mac-style checkbox.
case sliding
A style indicating that the switch appears as an on/off slider.
https://developer.apple.com/documentation/uikit/uiswitch/style-swift.enum/checkbox
- UIKit
- UISwitch
- UISwitch.Style
- UISwitch.Style.checkbox
Case
UISwitch.Style.checkbox
A style indicating that the switch appears as a Mac-style checkbox.
case checkbox
Mentioned in
Choosing a user interface idiom for your Mac app
Displaying a checkbox in your Mac app built with Mac Catalyst
Discussion
This style is only available to Mac apps built with Mac Catalyst that use the UIUserInterfaceIdiom.mac idiom. For more information about the Mac idiom, see Choosing a user interface idiom for your Mac app.
See Also
Styles
case automatic
A style indicating that the system chooses the appearance of the switch according to the current user interface idiom.
case sliding
A style indicating that the switch appears as an on/off slider.
https://developer.apple.com/documentation/uikit/uiuserinterfaceidiom/mac
- UIKit
- UIUserInterfaceIdiom
- UIUserInterfaceIdiom.mac
Case
UIUserInterfaceIdiom.mac
An interface designed for the Mac.
case mac
Mentioned in
Choosing a user interface idiom for your Mac app
Displaying a checkbox in your Mac app built with Mac Catalyst
Discussion
This idiom is available to Mac apps built with Mac Catalyst. For more information, see Choosing a user interface idiom for your Mac app.
See Also
Idioms
case unspecified
An unspecified idiom.
case phone
An interface designed for iPhone and iPod touch.
case pad
An interface designed for iPad.
case tv
An interface designed for tvOS and Apple TV.
case carPlay
An interface designed for an in-car experience.
case vision
An interface designed for visionOS and Apple Vision Pro.
https://developer.apple.com/documentation/uikit/uiswitch/title
- UIKit
- UISwitch
- title
Instance Property
title
The title displayed next to a checkbox-style switch.
@MainActor var title: String? { get set }
Mentioned in
Choosing a user interface idiom for your Mac app
Displaying a checkbox in your Mac app built with Mac Catalyst
Discussion
Set title only when the user interface idiom is UIUserInterfaceIdiom.mac; otherwise, a runtime exception occurs.
let showFavoritesAtTop = UISwitch() showFavoritesAtTop.preferredStyle = .checkbox if traitCollection.userInterfaceIdiom == .mac { showFavoritesAtTop.title = "Always show favorite recipes at the top" }
The switch ignores title when the value of style isn’t UISwitch.Style.checkbox.
See Also
Setting the display style
Present a switch control as a Mac-style checkbox when your app runs in the Mac user interface idiom.
var preferredStyle: UISwitch.Style
The preferred display style for the switch.
var style: UISwitch.Style
The display style for the switch.
enum Style
Styles that determine the appearance of the switch.
https://developer.apple.com/documentation/uikit/uiswitch/preferredstyle)
https://developer.apple.com/documentation/uikit/uiswitch/style-swift.enum/automatic)
https://developer.apple.com/documentation/uikit/uiswitch/style-swift.enum/checkbox).
https://developer.apple.com/documentation/uikit/uiuserinterfaceidiom/mac)
https://developer.apple.com/documentation/uikit/choosing-a-user-interface-idiom-for-your-mac-app).
.#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiswitch/title)
https://developer.apple.com/documentation/uikit/uiresponder/pressesbegan(_:with:)
#app-main)
- UIKit
- UIResponder
- pressesBegan(_:with:)
Instance Method
pressesBegan(_:with:)
Tells this object when a physical button is first pressed.
@MainActor func pressesBegan(
with event: UIPressesEvent? )
Parameters
presses
A set of UIPress instances that represent the new presses that occurred. The phase of each press is set to UIPress.Phase.began.
event
The event to which the presses belong.
Mentioned in
Handling key presses made on a physical keyboard
Discussion
UIKit calls this method when a new button is pressed by the user. Use this method to determine which button was pressed and to take any needed actions.
The default implementation of this method forwards the message up the responder chain. When creating your own subclasses, call super to forward any events that you don’t handle yourself.
See Also
Responding to press events
Tells this object when a value associated with a press has changed.
Tells the object when a button is released.
Tells this object when a system event (such as a low-memory warning) cancels a press event.
https://developer.apple.com/documentation/uikit/uipress/key
- UIKit
- UIPress
- key
Instance Property
key
The key pressed or released on a physical keyboard.
var key: UIKey? { get }
Mentioned in
Handling key presses made on a physical keyboard
Discussion
This property is nil when the press event isn’t from a keyboard; for example, a button press on an Apple TV remote.
See Also
Getting press attributes
var type: UIPress.PressType
The type of the specified press.
var phase: UIPress.Phase
The current press phase of the object.
var timestamp: TimeInterval
The time when the press occurred or when it was last mutated.
https://developer.apple.com/documentation/uikit/uikey/charactersignoringmodifiers
- UIKit
- UIKey
- charactersIgnoringModifiers
Instance Property
charactersIgnoringModifiers
A string that represents the text value of the key without modifier keys.
@MainActor var charactersIgnoringModifiers: String { get }
Mentioned in
Handling key presses made on a physical keyboard
Discussion
For Latin-based languages, always expect a lowercase property value. If the user is pressing only a modifier key, the property value is an empty string.
To check for special keys, compare charactersIgnoringModifiers to constants listed in Input strings for special keys.
See Also
Getting key characters
var characters: String
A string that represents the text value of the key combined with any active modifier keys.
https://developer.apple.com/documentation/uikit/uiresponder/pressesended(_:with:)
#app-main)
- UIKit
- UIResponder
- pressesEnded(_:with:)
Instance Method
pressesEnded(_:with:)
Tells the object when a button is released.
@MainActor func pressesEnded(
with event: UIPressesEvent? )
Parameters
presses
A set of UIPress instances that represent the buttons that the user is no longer pressing. The phase of each press is set to UIPress.Phase.ended.
event
The event to which the presses belong.
Mentioned in
Handling key presses made on a physical keyboard
Discussion
UIKit calls this method when the user stops pressing one or more buttons. Use this method to take any needed actions in response to the end of the press.The default implementation of this method forwards the message up the responder chain. When creating your own subclasses, call super to forward any events that you don’t handle yourself.
See Also
Responding to press events
Tells this object when a physical button is first pressed.
Tells this object when a value associated with a press has changed.
Tells this object when a system event (such as a low-memory warning) cancels a press event.
https://developer.apple.com/documentation/uikit/adding-hardware-keyboard-support-to-your-app
- UIKit
- Keyboards and input
- Adding hardware keyboard support to your app
Sample Code
Adding hardware keyboard support to your app
Enhance interactions with your app by handling raw keyboard events, writing custom keyboard shortcuts, and working with gesture recognizers.
Download
Xcode 12.0+
Overview
See Also
Physical keyboards
Handling key presses made on a physical keyboard
Detect when someone presses and releases keys on a physical keyboard.
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
class UIKey
An object that provides information about the state of a keyboard key.
enum UIKeyboardHIDUsage
A set of HID usage codes that identify the keys of a USB keyboard.
https://developer.apple.com/documentation/uikit/uikey
- UIKit
- UIKey
Class
UIKey
An object that provides information about the state of a keyboard key.
@MainActor class UIKey
Overview
UIKey provides relevant information about the current state of a key on a keyboard as a user presses and releases the key. To learn more, see Handling key presses made on a physical keyboard.
Topics
Determining key type
var keyCode: UIKeyboardHIDUsage
The HID usage code of the key.
var modifierFlags: UIKeyModifierFlags
The modifier keys pressed and held while the user presses the key.
Getting key characters
var characters: String
A string that represents the text value of the key combined with any active modifier keys.
var charactersIgnoringModifiers: String
A string that represents the text value of the key without modifier keys.
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSCopyingNSObjectProtocolSendable
See Also
Physical keyboards
Handling key presses made on a physical keyboard
Detect when someone presses and releases keys on a physical keyboard.
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
Adding hardware keyboard support to your app
Enhance interactions with your app by handling raw keyboard events, writing custom keyboard shortcuts, and working with gesture recognizers.
enum UIKeyboardHIDUsage
A set of HID usage codes that identify the keys of a USB keyboard.
https://developer.apple.com/documentation/uikit/uikeyboardhidusage
- UIKit
- UIKeyboardHIDUsage
Enumeration
UIKeyboardHIDUsage
A set of HID usage codes that identify the keys of a USB keyboard.
enum UIKeyboardHIDUsage
Topics
Alphabetical keys
case keyboardA
The raw usage code 4 (decimal)/04 (hexadecimal).
case keyboardB
The raw usage code 5 (decimal)/05 (hexadecimal).
case keyboardC
The raw usage code 6 (decimal)/06 (hexadecimal).
case keyboardD
The raw usage code 7 (decimal)/07 (hexadecimal).
case keyboardE
The raw usage code 8 (decimal)/08 (hexadecimal).
case keyboardF
The raw usage code 9 (decimal)/09 (hexadecimal).
case keyboardG
The raw usage code 10 (decimal)/0A (hexadecimal).
case keyboardH
The raw usage code 11 (decimal)/0B (hexadecimal).
case keyboardI
The raw usage code 12 (decimal)/0C (hexadecimal).
case keyboardJ
The raw usage code 13 (decimal)/0D (hexadecimal).
case keyboardK
The raw usage code 14 (decimal)/0E (hexadecimal).
case keyboardL
The raw usage code 15 (decimal)/0F (hexadecimal).
case keyboardM
The raw usage code 16 (decimal)/10 (hexadecimal).
case keyboardN
The raw usage code 17 (decimal)/11 (hexadecimal).
case keyboardO
The raw usage code 18 (decimal)/12 (hexadecimal).
case keyboardP
The raw usage code 19 (decimal)/13 (hexadecimal).
case keyboardQ
The raw usage code 20 (decimal)/14 (hexadecimal).
case keyboardR
The raw usage code 21 (decimal)/15 (hexadecimal).
case keyboardS
The raw usage code 22 (decimal)/16 (hexadecimal).
case keyboardT
The raw usage code 23 (decimal)/17 (hexadecimal).
case keyboardU
The raw usage code 24 (decimal)/18 (hexadecimal).
case keyboardV
The raw usage code 25 (decimal)/19 (hexadecimal).
case keyboardW
The raw usage code 26 (decimal)/1A (hexadecimal).
case keyboardX
The raw usage code 27 (decimal)/1B (hexadecimal).
case keyboardY
The raw usage code 28 (decimal)/1C (hexadecimal).
case keyboardZ
The raw usage code 29 (decimal)/1D (hexadecimal).
Numerical keys
case keyboard0
The raw usage code 39 (decimal)/27 (hexadecimal).
case keyboard1
The raw usage code 30 (decimal)/1E (hexadecimal).
case keyboard2
The raw usage code 31 (decimal)/1F (hexadecimal).
case keyboard3
The raw usage code 32 (decimal)/20 (hexadecimal).
case keyboard4
The raw usage code 33 (decimal)/21 (hexadecimal).
case keyboard5
The raw usage code 34 (decimal)/22 (hexadecimal).
case keyboard6
The raw usage code 35 (decimal)/23 (hexadecimal).
case keyboard7
The raw usage code 36 (decimal)/24 (hexadecimal).
case keyboard8
The raw usage code 37 (decimal)/25 (hexadecimal).
case keyboard9
The raw usage code 38 (decimal)/26 (hexadecimal).
Symbol keys
case keyboardBackslash
The raw usage code 49 (decimal)/31 (hexadecimal).
case keyboardCloseBracket
The raw usage code 48 (decimal)/30 (hexadecimal).
case keyboardComma
The raw usage code 54 (decimal)/36 (hexadecimal).
case keyboardEqualSign
The raw usage code 46 (decimal)/2E (hexadecimal).
case keyboardHyphen
The raw usage code 45 (decimal)/2D (hexadecimal).
case keyboardNonUSBackslash
The raw usage code 100 (decimal)/64 (hexadecimal).
case keyboardNonUSPound
The raw usage code 50 (decimal)/32 (hexadecimal).
case keyboardOpenBracket
The raw usage code 47 (decimal)/2F (hexadecimal).
case keyboardPeriod
The raw usage code 55 (decimal)/37 (hexadecimal).
case keyboardQuote
The raw usage code 52 (decimal)/34 (hexadecimal).
case keyboardSemicolon
The raw usage code 51 (decimal)/33 (hexadecimal).
case keyboardSeparator
The raw usage code 159 (decimal)/9F (hexadecimal).
case keyboardSlash
The raw usage code 56 (decimal)/38 (hexadecimal).
case keyboardSpacebar
The raw usage code 44 (decimal)/2C (hexadecimal).
Modifier keys
case keyboardCapsLock
The raw usage code 57 (decimal)/39 (hexadecimal).
case keyboardLeftAlt
The raw usage code 226 (decimal)/E2 (hexadecimal).
case keyboardLeftControl
The raw usage code 224 (decimal)/E0 (hexadecimal).
case keyboardLeftShift
The raw usage code 225 (decimal)/E1 (hexadecimal).
case keyboardLockingCapsLock
The raw usage code 130 (decimal)/82 (hexadecimal).
case keyboardLockingNumLock
The raw usage code 131 (decimal)/83 (hexadecimal).
case keyboardLockingScrollLock
The raw usage code 132 (decimal)/84 (hexadecimal).
case keyboardRightAlt
The raw usage code 230 (decimal)/E6 (hexadecimal).
case keyboardRightControl
The raw usage code 228 (decimal)/E4 (hexadecimal).
case keyboardRightShift
The raw usage code 229 (decimal)/E5 (hexadecimal).
case keyboardScrollLock
The raw usage code 71 (decimal)/47 (hexadecimal).
Navigation keys
case keyboardLeftArrow
The raw usage code 80 (decimal)/50 (hexadecimal).
case keyboardRightArrow
The raw usage code 79 (decimal)/4F (hexadecimal).
case keyboardUpArrow
The raw usage code 82 (decimal)/52 (hexadecimal).
case keyboardDownArrow
The raw usage code 81 (decimal)/51 (hexadecimal).
case keyboardPageUp
The raw usage code 75 (decimal)/4B (hexadecimal).
case keyboardPageDown
The raw usage code 78 (decimal)/4E (hexadecimal).
case keyboardHome
The raw usage code 74 (decimal)/4A (hexadecimal).
case keyboardEnd
The raw usage code 77 (decimal)/4D (hexadecimal).
case keyboardDeleteForward
The raw usage code 76 (decimal)/4C (hexadecimal).
case keyboardDeleteOrBackspace
The raw usage code 42 (decimal)/2A (hexadecimal).
case keyboardEscape
The raw usage code 41 (decimal)/29 (hexadecimal).
case keyboardInsert
The raw usage code 73 (decimal)/49 (hexadecimal).
case keyboardReturn
The raw usage code 158 (decimal)/9E (hexadecimal).
case keyboardTab
The raw usage code 43 (decimal)/2B (hexadecimal).
Function keys
case keyboardF1
The raw usage code 58 (decimal)/3A (hexadecimal).
case keyboardF2
The raw usage code 59 (decimal)/3B (hexadecimal).
case keyboardF3
The raw usage code 60 (decimal)/3C (hexadecimal).
case keyboardF4
The raw usage code 61 (decimal)/3D (hexadecimal).
case keyboardF5
The raw usage code 62 (decimal)/3E (hexadecimal).
case keyboardF6
The raw usage code 63 (decimal)/3F (hexadecimal).
case keyboardF7
The raw usage code 64 (decimal)/40 (hexadecimal).
case keyboardF8
The raw usage code 65 (decimal)/41 (hexadecimal).
case keyboardF9
The raw usage code 66 (decimal)/42 (hexadecimal).
case keyboardF10
The raw usage code 67 (decimal)/43 (hexadecimal).
case keyboardF11
The raw usage code 68 (decimal)/44 (hexadecimal).
case keyboardF12
The raw usage code 69 (decimal)/45 (hexadecimal).
case keyboardF13
The raw usage code 104 (decimal)/68 (hexadecimal).
case keyboardF14
The raw usage code 105 (decimal)/69 (hexadecimal).
case keyboardF15
The raw usage code 106 (decimal)/6A (hexadecimal).
case keyboardF16
The raw usage code 107 (decimal)/6B (hexadecimal).
case keyboardF17
The raw usage code 108 (decimal)/6C (hexadecimal).
case keyboardF18
The raw usage code 109 (decimal)/6D (hexadecimal).
case keyboardF19
The raw usage code 110 (decimal)/6E (hexadecimal).
case keyboardF20
The raw usage code 111 (decimal)/6F (hexadecimal).
case keyboardF21
The raw usage code 112 (decimal)/70 (hexadecimal).
case keyboardF22
The raw usage code 113 (decimal)/71 (hexadecimal).
case keyboardF23
The raw usage code 114 (decimal)/72 (hexadecimal).
case keyboardF24
The raw usage code 115 (decimal)/73 (hexadecimal).
Keypad keys
case keypad0
The raw usage code 98 (decimal)/62 (hexadecimal).
case keypad1
The raw usage code 89 (decimal)/59 (hexadecimal).
case keypad2
The raw usage code 90 (decimal)/5A (hexadecimal).
case keypad3
The raw usage code 91 (decimal)/5B (hexadecimal).
case keypad4
The raw usage code 92 (decimal)/5C (hexadecimal).
case keypad5
The raw usage code 93 (decimal)/5D (hexadecimal).
case keypad6
The raw usage code 94 (decimal)/5E (hexadecimal).
case keypad7
The raw usage code 95 (decimal)/5F (hexadecimal).
case keypad8
The raw usage code 96 (decimal)/60 (hexadecimal).
case keypad9
The raw usage code 97 (decimal)/61 (hexadecimal).
case keypadAsterisk
The raw usage code 85 (decimal)/55 (hexadecimal).
case keypadComma
The raw usage code 133 (decimal)/85 (hexadecimal).
case keypadEnter
The raw usage code 88 (decimal)/58 (hexadecimal).
case keypadEqualSign
The raw usage code 103 (decimal)/67 (hexadecimal).
case keypadEqualSignAS400
The raw usage code 134 (decimal)/86 (hexadecimal).
case keypadHyphen
The raw usage code 86 (decimal)/56 (hexadecimal).
case keypadNumLock
The raw usage code 83 (decimal)/53 (hexadecimal).
case keypadPeriod
The raw usage code 99 (decimal)/63 (hexadecimal).
case keypadPlus
The raw usage code 87 (decimal)/57 (hexadecimal).
case keypadSlash
The raw usage code 84 (decimal)/54 (hexadecimal).
Media keys
case keyboardPause
The raw usage code 72 (decimal)/48 (hexadecimal).
case keyboardStop
The raw usage code 120 (decimal)/78 (hexadecimal).
case keyboardMute
The raw usage code 127 (decimal)/7F (hexadecimal).
case keyboardVolumeUp
The raw usage code 128 (decimal)/80 (hexadecimal).
case keyboardVolumeDown
The raw usage code 129 (decimal)/81 (hexadecimal).
Input method keys
static var keyboardKanaSwitch: UIKeyboardHIDUsage
An alias for the LANG1 key on Japanese language keyboards from Apple.
static var keyboardHangul: UIKeyboardHIDUsage
An alias for the LANG1 key on Korean language keyboards.
static var keyboardAlphanumericSwitch: UIKeyboardHIDUsage
An alias for the LANG2 key on Japanese language keyboards from Apple.
static var keyboardHanja: UIKeyboardHIDUsage
An alias for the LANG2 key on Korean language keyboards.
static var keyboardKatakana: UIKeyboardHIDUsage
An alias for the LANG3 key on Japanese language keyboards.
static var keyboardHiragana: UIKeyboardHIDUsage
An alias for the LANG4 key on Japanese language keyboards.
static var keyboardZenkakuHankakuKanji: UIKeyboardHIDUsage
An alias for the LANG5 key on Japanese language keyboards.
case keyboardLANG1
The raw usage code 144 (decimal)/90 (hexadecimal).
case keyboardLANG2
The raw usage code 145 (decimal)/91 (hexadecimal).
case keyboardLANG3
The raw usage code 146 (decimal)/92 (hexadecimal).
case keyboardLANG4
The raw usage code 147 (decimal)/93 (hexadecimal).
case keyboardLANG5
The raw usage code 148 (decimal)/94 (hexadecimal).
case keyboardLANG6
The raw usage code 149 (decimal)/95 (hexadecimal).
case keyboardLANG7
The raw usage code 150 (decimal)/96 (hexadecimal).
case keyboardLANG8
The raw usage code 151 (decimal)/97 (hexadecimal).
case keyboardLANG9
The raw usage code 152 (decimal)/98 (hexadecimal).
case keyboardInternational1
The raw usage code 135 (decimal)/87 (hexadecimal).
case keyboardInternational2
The raw usage code 136 (decimal)/88 (hexadecimal).
case keyboardInternational3
The raw usage code 137 (decimal)/89 (hexadecimal).
case keyboardInternational4
The raw usage code 138 (decimal)/8A (hexadecimal).
case keyboardInternational5
The raw usage code 139 (decimal)/8B (hexadecimal).
case keyboardInternational6
The raw usage code 140 (decimal)/8C (hexadecimal).
case keyboardInternational7
The raw usage code 141 (decimal)/8D (hexadecimal).
case keyboardInternational8
The raw usage code 142 (decimal)/8E (hexadecimal).
case keyboardInternational9
The raw usage code 143 (decimal)/8F (hexadecimal).
Error keys
case keyboardErrorRollOver
The raw usage code 1 (decimal)/01 (hexadecimal).
case keyboardErrorUndefined
The raw usage code 3 (decimal)/03 (hexadecimal).
Other keys
case keyboardAgain
The raw usage code 121 (decimal)/79 (hexadecimal).
case keyboardAlternateErase
The raw usage code 153 (decimal)/99 (hexadecimal).
case keyboardApplication
The raw usage code 101 (decimal)/65 (hexadecimal).
case keyboardCancel
The raw usage code 155 (decimal)/9B (hexadecimal).
case keyboardClear
The raw usage code 156 (decimal)/9C (hexadecimal).
case keyboardClearOrAgain
The raw usage code 162 (decimal)/A2 (hexadecimal).
case keyboardCopy
The raw usage code 124 (decimal)/7C (hexadecimal).
case keyboardCrSelOrProps
The raw usage code 163 (decimal)/A3 (hexadecimal).
case keyboardCut
The raw usage code 129 (decimal)/7B (hexadecimal).
case keyboardExSel
The raw usage code 164 (decimal)/A4 (hexadecimal).
case keyboardExecute
The raw usage code 116 (decimal)/74 (hexadecimal).
case keyboardFind
The raw usage code 126 (decimal)/7E (hexadecimal).
case keyboardGraveAccentAndTilde
The raw usage code 53 (decimal)/35 (hexadecimal).
case keyboardHelp
The raw usage code 117 (decimal)/75 (hexadecimal).
case keyboardLeftGUI
The raw usage code 227 (decimal)/E3 (hexadecimal).
case keyboardMenu
The raw usage code 118 (decimal)/76 (hexadecimal).
case keyboardOper
The raw usage code 161 (decimal)/A1 (hexadecimal).
case keyboardOut
The raw usage code 160 (decimal)/A0 (hexadecimal).
case keyboardPOSTFail
The raw usage code 2 (decimal)/02 (hexadecimal).
case keyboardPaste
The raw usage code 125 (decimal)/7D (hexadecimal).
case keyboardPower
The raw usage code 102 (decimal)/66 (hexadecimal).
case keyboardPrintScreen
The raw usage code 70 (decimal)/46 (hexadecimal).
case keyboardPrior
The raw usage code 157 (decimal)/9D (hexadecimal).
case keyboardReturnOrEnter
The raw usage code 40 (decimal)/28 (hexadecimal).
case keyboardRightGUI
The raw usage code 231 (decimal)/E7 (hexadecimal).
case keyboardSelect
The raw usage code 119 (decimal)/77 (hexadecimal).
case keyboardSysReqOrAttention
The raw usage code 154 (decimal)/9A (hexadecimal).
case keyboardUndo
The raw usage code 122 (decimal)/7A (hexadecimal).
case keyboard_Reserved
The raw usage code 65535 (decimal)/FFFF (hexadecimal).
Initializers
init?(rawValue: CFIndex)
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Physical keyboards
Handling key presses made on a physical keyboard
Detect when someone presses and releases keys on a physical keyboard.
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
Adding hardware keyboard support to your app
Enhance interactions with your app by handling raw keyboard events, writing custom keyboard shortcuts, and working with gesture recognizers.
class UIKey
An object that provides information about the state of a keyboard key.
https://developer.apple.com/documentation/uikit/uiapplication),
https://developer.apple.com/documentation/uikit/using-responders-and-the-responder-chain-to-handle-events).
.#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiresponder/pressesbegan(_:with:))
https://developer.apple.com/documentation/uikit/uipress/key)
https://developer.apple.com/documentation/uikit/uikey/charactersignoringmodifiers)
https://developer.apple.com/documentation/uikit/uiresponder/pressesended(_:with:))
https://developer.apple.com/documentation/uikit/adding-hardware-keyboard-support-to-your-app)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uikey)
https://developer.apple.com/documentation/uikit/uikeyboardhidusage)
https://developer.apple.com/documentation/uikit/about-focus-interactions-for-apple-tv
- UIKit
- Focus-based navigation
- About focus interactions for Apple TV
Article
About focus interactions for Apple TV
Design and implement intuitive control schemes for menus and interactive user interface layouts.
Overview
On iOS devices, a user interacts directly with the touchscreen. On Apple TV, a remote or other input device is used to control the interface indirectly. Focus refers to the effect onscreen of external, indirect user input from an input device. As the user navigates through the interface, the next focusable item in the direction in which the user is navigating becomes focused, which triggers a focus update. If the focused item is selectable, the user selects it with the remote. Certain items, such as tab bars, are automatically selected after a slight delay.
The UIKit framework supports focus-based interfaces only, and in most cases this behavior is automatically provided. For apps with custom user interface components, you need to implement custom focus behavior.
Understanding the focus engine
The system within UIKit that controls focus and focus movement is called the focus engine. The focus engine listens for incoming focus-movement events in your app. When an event comes in, the focus engine automatically determines the next focusable item and notifies your app. This creates a consistent user experience across apps, provides automatic support for all current and future input methods, and helps developers concentrate on implementing their app’s unique behavior rather than defining or reinventing basic navigation.
Only the focus engine can explicitly update focus, meaning there’s no API for directly setting the focused item or moving focus in a particular direction. The focus engine updates focus only when the user sends a movement event or when the system or the app requests an update. Keep the following focus behaviors in mind when creating your layout design:
Not all items are focusable. If an item isn’t focusable, it’s ignored whenever focus is determined. Use the canBecomeFocused property to determine if an item is focusable.
Only a single item can have focus at any given time.
Users change focus by selecting a direction on the remote. UIKit then attempts to move the focus to a new user interface element in that direction. If the system finds another item that can accept focus in that direction, the found item gains focus. If no element is found in that direction, the currently focused item stays in focus and a movementDidFailNotification notification is broadcast.
Only the user can directionally change focus. Your app can’t programmatically search for a new element in a given direction. Although you can change focus programmatically, there are restrictions on how focus may change. Focus should almost always be under user control. For example, if the contents of a table view changed and the original focus element no longer exists, it’s reasonable to have your app programmatically select a new item to be in focus.
Focus is managed by the focus environment. When a focus environment gains focus, it can either keep the focus or give that focus to one of its own child focus environments. The focus environment it selects is its preferred focus environment. If a child focus environment is chosen, the child focus environment can also choose whether to keep focus or pass it to one of its child focus environments. This process drills down until a focus environment accepts focus for itself. The root view controller of the window also participates in the focus process. The root view controller’s preferredFocusEnvironments property is the first focus environment that’s selected to gain focus.
See Also
Focus interactions
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
Adding user-focusable elements to a tvOS app
Create intuitive and easily manipulated user-interactive controls for your tvOS app.
protocol UIFocusEnvironment
A set of methods that define the focus behavior for a branch of the view hierarchy.
class UIFocusSystem
Queries and reevaluates the currently focused item.
class UIFocusUpdateContext
An object that provides information relevant to a specific focus update from one view to another.
protocol UIFocusItem
An object that can become focused.
class UIFocusMovementHint
Provides movement hint information for the focused item.
protocol UIFocusItemContainer
The container responsible for providing geometric context to focus items within a given focus environment.
protocol UIFocusItemScrollableContainer
A type of focus item container that supports automatic scrolling of focusable content.
struct UIFocusGroupPriority
The importance of an item within a focus group, used by the focus system to determine the group’s primary item.
https://developer.apple.com/documentation/uikit/adding-user-focusable-elements-to-a-tvos-app
- UIKit
- Focus-based navigation
- Adding user-focusable elements to a tvOS app
Article
Adding user-focusable elements to a tvOS app
Create intuitive and easily manipulated user-interactive controls for your tvOS app.
Overview
On Apple TV, people use a remote or game controller to navigate through interface elements like movie posters, apps, or buttons, highlighting each item as they come to it. The highlighted item is said to be focused or in focus. It appears elevated or otherwise distinct from other items. An item is considered focused when the user has highlighted it, but not selected it. The user moves focus by navigating through different UI items, which triggers a focus update.
Add focusable items to the view
In Xcode, search the Library pane for the item you want to add to your app, and drag it to your app’s storyboard. Several UIKit elements are focusable by default, including buttons ( UIButton), text fields ( UITextField), and table cells ( UITableViewCell). The top-left item is in focus when your app launches. (In right-to-left languages, the top-right item is initially in focus.) You don’t need to do anything to UIKit elements that are focusable by default. However, you can add SceneKit and SpriteKit nodes as focusable elements. To make a SceneKit or SpriteKit node focusable, set the focusBehavior property of the node to focusable, as shown below.
node.focusBehavior = .focusable
Design your layout in a grid pattern
The easiest way to ensure that focus moves between focusable items is to arrange the items in a grid pattern. Swiping on the remote triggers the focus engine—the system that controls focus and movement—to find all of the focusable items in the direction of the swipe. The first item found then becomes the newly focused item. The following image shows the items found by the focus engine when the user swipes right, and the resulting focused item.
The following image shows the items found by the focus engine when the user swipes down, and the resulting focused item.
When the focus engine doesn’t find any items in the direction of the swipe, by default the focused item doesn’t change, as shown in the following image.
When necessary, you can change the default behavior by using UIFocusGuide to redirect focus to other focusable items in the user interface.
See Also
Focus interactions
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
About focus interactions for Apple TV
Design and implement intuitive control schemes for menus and interactive user interface layouts.
protocol UIFocusEnvironment
A set of methods that define the focus behavior for a branch of the view hierarchy.
class UIFocusSystem
Queries and reevaluates the currently focused item.
class UIFocusUpdateContext
An object that provides information relevant to a specific focus update from one view to another.
protocol UIFocusItem
An object that can become focused.
class UIFocusMovementHint
Provides movement hint information for the focused item.
protocol UIFocusItemContainer
The container responsible for providing geometric context to focus items within a given focus environment.
protocol UIFocusItemScrollableContainer
A type of focus item container that supports automatic scrolling of focusable content.
struct UIFocusGroupPriority
The importance of an item within a focus group, used by the focus system to determine the group’s primary item.
https://developer.apple.com/documentation/uikit/uifocussystem
- UIKit
- UIFocusSystem
Class
UIFocusSystem
Queries and reevaluates the currently focused item.
@MainActor class UIFocusSystem
Overview
Use a UIFocusSystem object to obtain the focus-related state for the objects of your app. You can get state information for your app’s views, view controllers, windows, and other objects that adopt the UIFocusEnvironment protocol. The UIFocusSystem object lists the currently focused item, if any, for a window or view hierarchy. You can use it to force the system to update the focus state, and you can register custom sounds to be played during focus changes.
Topics
Getting a focus system object
init?(for: any UIFocusEnvironment)
Retrieves a focus system object that contains the state information for the specified object.
Deprecated
Retrieves the focus system for the specified environment.
Getting the currently focused item
var focusedItem: (any UIFocusItem)?
The item that’s currently focused.
Managing focus updates
func requestFocusUpdate(to: any UIFocusEnvironment)
Submits a request to update the focus state of the specified object.
func updateFocusIfNeeded()
Forces the system to act on a pending focus update for the current environment.
Registering custom sounds
class func register(URL, forSoundIdentifier: UIFocusSoundIdentifier)
Registers the specified sound file with the focus engine.
Responding to focus-related keys and notifications
class let animationCoordinatorUserInfoKey: String
Updates the animation coordinator.
class let didUpdateNotification: NSNotification.Name
The focus for the UI has been updated.
class let focusUpdateContextUserInfoKey: String
Updates the context key.
class let movementDidFailNotification: NSNotification.Name
The focus failed to move to another item.
Structures
struct DidUpdateMessage Beta
struct MovementDidFailMessage Beta
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendable
See Also
Focus interactions
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
About focus interactions for Apple TV
Design and implement intuitive control schemes for menus and interactive user interface layouts.
Adding user-focusable elements to a tvOS app
Create intuitive and easily manipulated user-interactive controls for your tvOS app.
protocol UIFocusEnvironment
A set of methods that define the focus behavior for a branch of the view hierarchy.
class UIFocusUpdateContext
An object that provides information relevant to a specific focus update from one view to another.
protocol UIFocusItem
An object that can become focused.
class UIFocusMovementHint
Provides movement hint information for the focused item.
protocol UIFocusItemContainer
The container responsible for providing geometric context to focus items within a given focus environment.
protocol UIFocusItemScrollableContainer
A type of focus item container that supports automatic scrolling of focusable content.
struct UIFocusGroupPriority
The importance of an item within a focus group, used by the focus system to determine the group’s primary item.
https://developer.apple.com/documentation/uikit/uifocusupdatecontext
- UIKit
- UIFocusUpdateContext
Class
UIFocusUpdateContext
An object that provides information relevant to a specific focus update from one view to another.
@MainActor class UIFocusUpdateContext
Overview
Focus update context objects are ephemeral and are usually discarded after the update is finished. The UIFocus APIs create a single high-level software interface for controlling focus in apps that use focus-based input.
Topics
Locating focus direction
var previouslyFocusedView: UIView?
The view that was focused before the focus update.
var nextFocusedView: UIView?
The view that takes the focus after the focus update.
var focusHeading: UIFocusHeading
The heading in which the focus update is occurring.
struct UIFocusHeading
The general type of an event.
Getting related focus items
var previouslyFocusedItem: (any UIFocusItem)?
The item that was focused before the update.
var nextFocusedItem: (any UIFocusItem)?
The item to be focused after the update.
Responding to focus-related keys and notifications
class let didUpdateNotification: NSNotification.Name
The focus for the UI has been updated.
class let movementDidFailNotification: NSNotification.Name
The focus failed to move to another item.
class let animationCoordinatorUserInfoKey: String
Updates the animation coordinator.
class let focusUpdateContextUserInfoKey: String
Updates the context key.
Relationships
Inherits From
NSObject
Inherited By
UICollectionViewFocusUpdateContextUITableViewFocusUpdateContext
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendable
See Also
Focus interactions
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
About focus interactions for Apple TV
Design and implement intuitive control schemes for menus and interactive user interface layouts.
Adding user-focusable elements to a tvOS app
Create intuitive and easily manipulated user-interactive controls for your tvOS app.
protocol UIFocusEnvironment
A set of methods that define the focus behavior for a branch of the view hierarchy.
class UIFocusSystem
Queries and reevaluates the currently focused item.
protocol UIFocusItem
An object that can become focused.
class UIFocusMovementHint
Provides movement hint information for the focused item.
protocol UIFocusItemContainer
The container responsible for providing geometric context to focus items within a given focus environment.
protocol UIFocusItemScrollableContainer
A type of focus item container that supports automatic scrolling of focusable content.
struct UIFocusGroupPriority
The importance of an item within a focus group, used by the focus system to determine the group’s primary item.
https://developer.apple.com/documentation/uikit/uifocusmovementhint
- UIKit
- UIFocusMovementHint
Class
UIFocusMovementHint
Provides movement hint information for the focused item.
class UIFocusMovementHint
Topics
Moving focus
var movementDirection: CGVector
A vector representing how close focus is to moving to another item in the swiped direction.
Transforming a hint
var interactionTransform: CATransform3D
A 3D transform that contains the combined transformations of perspective, rotation, and translation.
var perspectiveTransform: CATransform3D
A 3D transform that represents a perspective matrix to be applied to match UIKit interaction hinting.
var rotation: CGVector
A vector to apply to a transform to match system interaction hinting.
var translation: CGVector
Relationships
Inherits From
NSObject
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCopyingNSObjectProtocol
See Also
Focus interactions
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
About focus interactions for Apple TV
Design and implement intuitive control schemes for menus and interactive user interface layouts.
Adding user-focusable elements to a tvOS app
Create intuitive and easily manipulated user-interactive controls for your tvOS app.
protocol UIFocusEnvironment
A set of methods that define the focus behavior for a branch of the view hierarchy.
class UIFocusSystem
Queries and reevaluates the currently focused item.
class UIFocusUpdateContext
An object that provides information relevant to a specific focus update from one view to another.
protocol UIFocusItem
An object that can become focused.
protocol UIFocusItemContainer
The container responsible for providing geometric context to focus items within a given focus environment.
protocol UIFocusItemScrollableContainer
A type of focus item container that supports automatic scrolling of focusable content.
struct UIFocusGroupPriority
The importance of an item within a focus group, used by the focus system to determine the group’s primary item.
https://developer.apple.com/documentation/uikit/uifocusitemscrollablecontainer
- UIKit
- UIFocusItemScrollableContainer
Protocol
UIFocusItemScrollableContainer
A type of focus item container that supports automatic scrolling of focusable content.
@MainActor protocol UIFocusItemScrollableContainer : UIFocusItemContainer
Overview
The focus engine scrolls the container to keep items onscreen as they become focused. This is done by repeatedly setting contentOffset.
Topics
Retrieving the content size
var contentOffset: CGPoint
The current content offset for the scrollable container.
Required
var contentSize: CGSize
The total size of the content contained by this container.
var visibleSize: CGSize
The visible size of the scrollable container.
Relationships
Inherits From
NSObjectProtocolUIFocusItemContainer
Conforming Types
UICollectionViewUIScrollViewUITableViewUITextView
See Also
Focus interactions
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
About focus interactions for Apple TV
Design and implement intuitive control schemes for menus and interactive user interface layouts.
Adding user-focusable elements to a tvOS app
Create intuitive and easily manipulated user-interactive controls for your tvOS app.
protocol UIFocusEnvironment
A set of methods that define the focus behavior for a branch of the view hierarchy.
class UIFocusSystem
Queries and reevaluates the currently focused item.
class UIFocusUpdateContext
An object that provides information relevant to a specific focus update from one view to another.
protocol UIFocusItem
An object that can become focused.
class UIFocusMovementHint
Provides movement hint information for the focused item.
protocol UIFocusItemContainer
The container responsible for providing geometric context to focus items within a given focus environment.
struct UIFocusGroupPriority
The importance of an item within a focus group, used by the focus system to determine the group’s primary item.
https://developer.apple.com/documentation/uikit/uifocusgrouppriority
- UIKit
- UIFocusGroupPriority
Structure
UIFocusGroupPriority
The importance of an item within a focus group, used by the focus system to determine the group’s primary item.
iOSiPadOSMac CatalysttvOSvisionOS
struct UIFocusGroupPriority
Topics
Constants
static let ignored: UIFocusGroupPriority
The lowest focus group priority, assigned by default.
static let previouslyFocused: UIFocusGroupPriority
The focus group priority of a previously focused item.
static let prioritized: UIFocusGroupPriority
The focus group priority that indicates an item is more important than others.
static let currentlyFocused: UIFocusGroupPriority
The focus group priority of the currently focused item, the highest possible priority.
Initializing a focus group priority
init(Int)
Creates a focus group priority with the specified value.
init(rawValue: Int)
Creates a focus group priority with the specified raw value.
Relationships
Conforms To
BitwiseCopyableEquatableHashableRawRepresentableSendableSendableMetatype
See Also
Focus interactions
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
About focus interactions for Apple TV
Design and implement intuitive control schemes for menus and interactive user interface layouts.
Adding user-focusable elements to a tvOS app
Create intuitive and easily manipulated user-interactive controls for your tvOS app.
protocol UIFocusEnvironment
A set of methods that define the focus behavior for a branch of the view hierarchy.
class UIFocusSystem
Queries and reevaluates the currently focused item.
class UIFocusUpdateContext
An object that provides information relevant to a specific focus update from one view to another.
protocol UIFocusItem
An object that can become focused.
class UIFocusMovementHint
Provides movement hint information for the focused item.
protocol UIFocusItemContainer
The container responsible for providing geometric context to focus items within a given focus environment.
protocol UIFocusItemScrollableContainer
A type of focus item container that supports automatic scrolling of focusable content.
https://developer.apple.com/documentation/uikit/about-focus-interactions-for-apple-tv)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/adding-user-focusable-elements-to-a-tvos-app)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uifocussystem)
https://developer.apple.com/documentation/uikit/uifocusupdatecontext)
https://developer.apple.com/documentation/uikit/uifocusmovementhint)
https://developer.apple.com/documentation/uikit/uifocusitemscrollablecontainer)
https://developer.apple.com/documentation/uikit/uifocusgrouppriority)
https://developer.apple.com/documentation/uikit/uihovergesturerecognizer/altitudeangle
- UIKit
- UIHoverGestureRecognizer
- altitudeAngle
Instance Property
altitudeAngle
A value that represents the altitude angle of the hovering pointing device.
@MainActor var altitudeAngle: CGFloat { get }
Discussion
This value is 0 for devices that don’t support altitude.
See Also
Supporting Apple Pencil hover
A value that represents the azimuth angle of the hovering pointing device in the specified view.
A value that represents the azimuth unit vector of the hovering pointing device in the specified view.
var rollAngle: CGFloat
A value that represents the current barrel-roll angle of Apple Pencil.
var zOffset: CGFloat
A value that represents the normalized distance between the screen and a hovering pointing device, such as Apple Pencil.
https://developer.apple.com/documentation/uikit/uihovergesturerecognizer/azimuthangle(in:)
#app-main)
- UIKit
- UIHoverGestureRecognizer
- azimuthAngle(in:)
Instance Method
azimuthAngle(in:)
A value that represents the azimuth angle of the hovering pointing device in the specified view.
@MainActor
Parameters
view
The view the angle is relative to.
Return Value
A CGFloat that represents the azimuth angle of the hovering pointing device.
Discussion
If the specified view is nil, the method returns the azimuth angle of the hovering pointing device in the gesture recognizer’s window.
This method returns 0 for devices that don’t support azimuth.
See Also
Supporting Apple Pencil hover
var altitudeAngle: CGFloat
A value that represents the altitude angle of the hovering pointing device.
A value that represents the azimuth unit vector of the hovering pointing device in the specified view.
var rollAngle: CGFloat
A value that represents the current barrel-roll angle of Apple Pencil.
var zOffset: CGFloat
A value that represents the normalized distance between the screen and a hovering pointing device, such as Apple Pencil.
https://developer.apple.com/documentation/uikit/uihovergesturerecognizer/azimuthunitvector(in:)
https://developer.apple.com/documentation/uikit/uihovergesturerecognizer/rollangle
- UIKit
- UIHoverGestureRecognizer
- rollAngle
Instance Property
rollAngle
A value that represents the current barrel-roll angle of Apple Pencil.
@MainActor var rollAngle: CGFloat { get }
Discussion
For models of Apple Pencil that don’t support barrel-roll angle data, the value of this property is 0.
See Also
Supporting Apple Pencil hover
var altitudeAngle: CGFloat
A value that represents the altitude angle of the hovering pointing device.
A value that represents the azimuth angle of the hovering pointing device in the specified view.
A value that represents the azimuth unit vector of the hovering pointing device in the specified view.
var zOffset: CGFloat
A value that represents the normalized distance between the screen and a hovering pointing device, such as Apple Pencil.
https://developer.apple.com/documentation/uikit/uihovergesturerecognizer/zoffset
- UIKit
- UIHoverGestureRecognizer
- zOffset
Instance Property
zOffset
A value that represents the normalized distance between the screen and a hovering pointing device, such as Apple Pencil.
@MainActor var zOffset: CGFloat { get }
Discussion
This value is 1 at the maximum distance from the screen and approaches 0 as the pointing device gets closer to the screen. This value is 0 for devices that don’t support zOffset.
For example, a drawing app might use the value of this property to generate a preview that indicates where a hovering Apple Pencil touches down on an iPad screen. For more information, see Adopting hover support for Apple Pencil.
See Also
Supporting Apple Pencil hover
var altitudeAngle: CGFloat
A value that represents the altitude angle of the hovering pointing device.
A value that represents the azimuth angle of the hovering pointing device in the specified view.
A value that represents the azimuth unit vector of the hovering pointing device in the specified view.
var rollAngle: CGFloat
A value that represents the current barrel-roll angle of Apple Pencil.
https://developer.apple.com/documentation/uikit/uigesturerecognizer
- UIKit
- UIGestureRecognizer
Class
UIGestureRecognizer
The base class for concrete gesture recognizers.
tvOS
@MainActor class UIGestureRecognizer
Overview
A gesture recognizer decouples the logic for recognizing a sequence of touches (or other input) and acting on that recognition. When one of these objects recognizes a common gesture or, in some cases, a change in the gesture, it sends an action message to each designated target object.
The concrete subclasses of UIGestureRecognizer are the following:
-
UITapGestureRecognizer -
UIPinchGestureRecognizer -
UIRotationGestureRecognizer -
UISwipeGestureRecognizer -
UIPanGestureRecognizer -
UIScreenEdgePanGestureRecognizer -
UILongPressGestureRecognizer -
UIHoverGestureRecognizer
The UIGestureRecognizer class defines a set of common behaviors that can be configured for all concrete gesture recognizers. It can also communicate with its delegate (an object that adopts the UIGestureRecognizerDelegate protocol), thereby enabling finer-grained customization of some behaviors.
A gesture recognizer operates on touches hit-tested to a specific view and all of that view’s subviews. It thus must be associated with that view. To make that association you must call the UIView method addGestureRecognizer(_:). A gesture recognizer doesn’t participate in the view’s responder chain.
A gesture recognizer has one or more target-action pairs associated with it. If there are multiple target-action pairs, they’re discrete, and not cumulative. Recognition of a gesture results in the dispatch of an action message to a target for each of the associated pairs. The action methods invoked must conform to one of the following signatures:
@IBAction func myActionMethod() @IBAction func myActionMethod(_ sender: UIGestureRecognizer)
- (IBAction)handleGesture;
- (IBAction)handleGesture:(UIGestureRecognizer *)gestureRecognizer;
Methods conforming to the latter signature permit the target in some cases to query the gesture recognizer sending the message for additional information. For example, the target could ask a UIRotationGestureRecognizer object for the angle of rotation (in radians) since the last invocation of the action method for this gesture. Clients of gesture recognizers can also ask for the location of a gesture by calling location(in:) or location(ofTouch:in:).
The gesture interpreted by a gesture recognizer can be either discrete or continuous. A discrete gesture, such as a double tap, occurs but once in a multi-touch sequence and results in a single action sent. However, when a gesture recognizer interprets a continuous gesture such as a rotation gesture, it sends an action message for each incremental change until the multi-touch sequence concludes.
A window delivers touch events to a gesture recognizer before it delivers them to the hit-tested view attached to the gesture recognizer. Generally, if a gesture recognizer analyzes the stream of touches in a multi-touch sequence and doesn’t recognize its gesture, the view receives the full complement of touches. If a gesture recognizer recognizes its gesture, the remaining touches for the view are canceled. The usual sequence of actions in gesture recognition follows a path determined by default values of the cancelsTouchesInView, delaysTouchesBegan, delaysTouchesEnded properties:
-
cancelsTouchesInView— If a gesture recognizer recognizes its gesture, it unbinds the remaining touches of that gesture from their view (so the window won’t deliver them). The window cancels the previously delivered touches with a (touchesCancelled(_:with:)) message. If a gesture recognizer doesn’t recognize its gesture, the view receives all touches in the multi-touch sequence. -
delaysTouchesBegan— As long as a gesture recognizer, when analyzing touch events, hasn’t failed recognition of its gesture, the window withholds delivery of touch objects in theUITouch.Phase.beganphase to the attached view. If the gesture recognizer subsequently recognizes its gesture, the view doesn’t receive these touch objects. If the gesture recognizer doesn’t recognize its gesture, the window delivers these objects in an invocation of the view’stouchesBegan(_:with:)method (and possibly a follow-uptouchesMoved(_:with:)invocation to inform it of the touches current location). -
delaysTouchesEnded— As long as a gesture recognizer, when analyzing touch events, hasn’t failed recognition of its gesture, the window withholds delivery of touch objects in theUITouch.Phase.endedphase to the attached view. If the gesture recognizer subsequently recognizes its gesture, the touches are canceled (in atouchesCancelled(_:with:)message). If the gesture recognizer doesn’t recognize its gesture, the window delivers these objects in an invocation of the view’stouchesEnded(_:with:)method.
Note that “recognize” in the above descriptions doesn’t necessarily equate to a transition to the Recognized state.
Subclassing notes
You may create a subclass of UIGestureRecognizer that recognizes a distinctive gesture — for example, a “check mark” gesture. If you’re going to create such a concrete gesture recognizer, be sure to import the UIGestureRecognizerSubclass.h header file (for Objective-C) or the UIKit.UIGestureRecognizerSubclass module (for Swift). This file declares all the methods and properties a subclass must either override, call, or reset.
Gesture recognizers operate within a predefined state machine, transitioning to subsequent states as they handle multi-touch events. The states and their possible transitions differ for continuous and discrete gestures. All gesture recognizers begin a multi-touch sequence in the Possible state ( UIGestureRecognizer.State.possible). Discrete gestures transition from Possible to either Recognized ( recognized) or Failed ( UIGestureRecognizer.State.failed), depending on whether they successfully interpret the gesture or not. If the gesture recognizer transitions to Recognized, it sends its action message to its target.
For continuous gestures, the state transitions a gesture recognizer might make are more numerous, as indicated in the following sequence:
The Changed state is optional and may occur multiple times before the Cancelled or Ended state is reached. The gesture recognizer sends action messages at each state transition. Thus for a continuous gesture such as a pinch, action messages are sent as the two fingers move toward or away from each other. The enum constants representing these states are of type UIGestureRecognizer.State. (Note that the constants for Recognized and Ended states are synonymous.)
Subclasses must set the state property to the appropriate value when they transition between states.
Methods to override
The methods that subclasses must override are described in Implementing subclasses. Subclasses must also periodically reset the state property (as described above) and may call the ignore(_:for:) method.
Special considerations
The state property is declared in UIGestureRecognizer.h as being read-only. This property declaration is intended for clients of gesture recognizers. Subclasses of UIGestureRecognizer must import the UIGestureRecognizerSubclass.h header file (for Objective-C) or the UIKit.UIGestureRecognizerSubclass module (for Swift). This file contains a redeclaration of state that makes it read-write.
Topics
Initializing a gesture recognizer
init(target: Any?, action: Selector?)
Creates a gesture recognizer with a target and an action selector.
convenience init?(coder: NSCoder)
Creates a gesture recognizer from data in an unarchiver.
convenience init()
Creates a gesture recognizer.
Managing gesture-related interactions
var delegate: (any UIGestureRecognizerDelegate)?
The delegate of the gesture recognizer.
protocol UIGestureRecognizerDelegate
A set of methods implemented by the delegate of a gesture recognizer to fine-tune an app’s gesture-recognition behavior.
Adding and removing targets and actions
func addTarget(Any, action: Selector)
Adds a target and an action to a gesture-recognizer object.
func removeTarget(Any?, action: Selector?)
Removes a target and an action from a gesture-recognizer object.
Getting the touches and location of a gesture
Returns the point computed as the location in a given view of the gesture represented by the gesture recognizer.
Returns the location of one of the gesture’s touches in the local coordinate system of a given view.
var numberOfTouches: Int
The number of touches involved in the gesture represented by the gesture recognizer.
Getting the recognizer’s state and view
var state: UIGestureRecognizer.State
The current state of the gesture recognizer.
enum State
Constants that represent the current state a gesture recognizer is in.
var view: UIView?
The view the gesture recognizer is attached to.
var isEnabled: Bool
A Boolean property that indicates whether the gesture recognizer is enabled.
var buttonMask: UIEvent.ButtonMask
A bit mask of the buttons in the gesture represented by the gesture recognizer.
var modifierFlags: UIKeyModifierFlags
The bit mask of modifier flags in the gesture represented by the gesture recognizer.
Canceling and delaying touches
var cancelsTouchesInView: Bool
A Boolean value that determines whether touches are delivered to a view when a gesture is recognized.
var delaysTouchesBegan: Bool
A Boolean value that determines whether the gesture recognizer delays sending touches in a begin phase to its view.
var delaysTouchesEnded: Bool
A Boolean value that determines whether the gesture recognizer delays sending touches in an end phase to its view.
Specifying dependencies between gesture recognizers
func require(toFail: UIGestureRecognizer)
Creates a dependency relationship between the gesture recognizer and another gesture recognizer when the objects are created.
Recognizing different gestures
var allowedPressTypes: [NSNumber]
An array of press types used to distinguish the type of button press.
var allowedTouchTypes: [NSNumber]
An array of touch types used to distinguish type of touches.
var requiresExclusiveTouchType: Bool
A Boolean value that indicates whether the gesture recognizer considers touches of different types simultaneously.
Debugging gesture recognizers
var name: String?
The unique name of the gesture recognizer.
Implementing subclasses
The UIKit.UIGestureRecognizerSubclass module (Swift) and UIGestureRecognizerSubclass.h header file (Objective-C) contain a class extension that declares methods intended to be called or overridden only by subclasses of UIGestureRecognizer. Clients that merely use concrete subclasses of UIGestureRecognizer must never call these methods (except for those noted).
Sent to the gesture recognizer when one or more fingers touch down in the associated view.
Sent to the gesture recognizer when one or more fingers move in the associated view.
Sent to the gesture recognizer when one or more fingers lift from the associated view.
Sent to the gesture recognizer when a system event (such as an incoming phone call) cancels a touch event.
Sent to the gesture recognizer when the estimated properties for a touch have changed so that they are no longer estimated, or an update is no longer expected.
func reset()
Overridden to reset internal state when a gesture recognition attempt completes.
func ignore(UITouch, for: UIEvent)
Tells the gesture recognizer to ignore a specific touch of the given event.
Overridden to indicate that the specified gesture recognizer can prevent the receiver from recognizing a gesture.
Overridden to indicate that the receiver can prevent the specified gesture recognizer from recognizing its gesture.
Overridden to indicate that the receiver requires the specified gesture recognizer to fail.
Overridden to indicate that the receiver should be required to fail by the specified gesture recognizer.
func ignore(UIPress, for: UIPressesEvent)
Tells the gesture recognizer to ignore a specific press of the given event.
Sent to the receiver when a physical button is pressed in the associated view.
Sent to the receiver when the force of the press has changed in the associated view.
Sent to the receiver when a button is released from the associated view.
Sent to the receiver when a system event (such as a low-memory warning) cancels a press event.
Relationships
Inherits From
NSObject
Inherited By
UIHoverGestureRecognizerUILongPressGestureRecognizerUIPanGestureRecognizerUIPinchGestureRecognizerUIRotationGestureRecognizerUISwipeGestureRecognizerUITapGestureRecognizer
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendable
See Also
Custom gestures
Discover when and how to build your own gesture recognizers.
Supporting gesture interaction in your apps
Enrich your app’s user experience by supporting standard and custom gesture interaction.
https://developer.apple.com/documentation/uikit/uihovergesturerecognizer/altitudeangle)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uihovergesturerecognizer/azimuthangle(in:))
https://developer.apple.com/documentation/uikit/uihovergesturerecognizer/azimuthunitvector(in:))
)#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uihovergesturerecognizer/rollangle)
https://developer.apple.com/documentation/uikit/uihovergesturerecognizer/zoffset)
https://developer.apple.com/documentation/uikit/uigesturerecognizer)
https://developer.apple.com/documentation/uikit/uimenusystem
- UIKit
- UIMenuSystem
Class
UIMenuSystem
An object representing a main or contextual menu system.
@MainActor class UIMenuSystem
Overview
A menu system groups root menus together. The main system has only one root menu while the context system can have multiple root menus, each built in different UIResponder objects like a view controller.
Use UIMenuSystem in your implementation of buildMenu(with:) to isolate changes to a specific system.
override func buildMenu(with builder: UIMenuBuilder) { super.buildMenu(with: builder)
// Ensure that the builder is modifying the menu bar system. guard builder.system == UIMenuSystem.main else { return }
// ... }
You can also use a menu system to rebuild or revalidate menus as changes occur in your app. To rebuild a menu, call the setNeedsRebuild() method. Call setNeedsRevalidate() when you need the menu system to revalidate a menu.
For more information, see Adding menus and shortcuts to the menu bar and user interface.
Topics
Getting a menu system
class var main: UIMenuSystem
The main menu system.
class var context: UIMenuSystem
The context menu system.
Rebuilding a menu system
func setNeedsRebuild()
Tells the menu system to rebuild all of its menus.
Revalidating a menu system
func setNeedsRevalidate()
Tells the menu system to validate all of its menus.
Setting group preferences
enum ElementGroupPreference Beta
Relationships
Inherits From
NSObject
Inherited By
UIContextMenuSystemUIMainMenuSystem
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSObjectProtocolSendable
See Also
App menus
class UIMenu
A container for grouping related menu elements in an app menu or contextual menu.
protocol UIMenuBuilder
An interface for adding and removing menus from a menu system.
class UIMainMenuSystem
Beta
https://developer.apple.com/documentation/uikit/uicontextmenuinteractiondelegate
- UIKit
- UIContextMenuInteractionDelegate
Protocol
UIContextMenuInteractionDelegate
The methods for providing the set of actions to perform on your content, and for customizing the preview of that content.
@MainActor protocol UIContextMenuInteractionDelegate : NSObjectProtocol
Mentioned in
Building a desktop-class iPad app
Overview
Use this protocol to provide UIKit with the contextual menu that you want to display. When a UIContextMenuInteraction object detects an appropriate interaction, it calls the contextMenuInteraction(_:configurationForMenuAtLocation:) method of your delegate. You use that method to specify the basic configuration details for your interface. In addition to your contextual menu, you can tell UIKit whether you want it to display a default preview interface or a custom view controller that you provide. You can also specify options for how you want UIKit to animate the presentation and dismissal of that interface.
For additional information about how to implement contextual menus, see Adding context menus in your app.
Topics
Providing the preview configuration data
Returns the configuration data to use when previewing the content.
Required
class UIContextMenuConfiguration
An object containing the configuration details for the contextual menu.
Customizing the preview animations
Asks the delegate for a preview of the item with the specified identifier when a context-menu interaction begins.
Asks the delegate for a preview of the item with the specified identifier when a context-menu interaction ends.
Adding menus and shortcuts to the menu bar and user interface
Provide quick access to useful actions by adding menus and keyboard shortcuts to your Mac app built with Mac Catalyst.
Responding to the menu’s appearance
func contextMenuInteraction(UIContextMenuInteraction, willPerformPreviewActionForMenuWith: UIContextMenuConfiguration, animator: any UIContextMenuInteractionCommitAnimating)
Informs the delegate when a preview action begins.
protocol UIContextMenuInteractionCommitAnimating
Methods adopted by system-supplied animator objects when committing preview-related animations.
Handling animations
func contextMenuInteraction(UIContextMenuInteraction, willDisplayMenuFor: UIContextMenuConfiguration, animator: (any UIContextMenuInteractionAnimating)?)
Informs the delegate when a menu display begins.
func contextMenuInteraction(UIContextMenuInteraction, willEndFor: UIContextMenuConfiguration, animator: (any UIContextMenuInteractionAnimating)?)
Informs the delegate when a menu display ends.
protocol UIContextMenuInteractionAnimating
Methods adopted by system-supplied animator objects when interacting with context menus.
Deprecated
Returns the source view to use when animating the appearance of the preview interface.
Deprecated
Returns the destination view to use when animating the appearance of the preview interface.
Relationships
Inherits From
NSObjectProtocol
Conforming Types
UIButtonUIColorWellUIControlUIDatePickerUIPageControlUIPasteControlUIRefreshControlUISearchTextFieldUISegmentedControlUISliderUIStepperUISwitchUITextField
See Also
Contextual menus
class UIContextMenuSystem
The context menu system.
Beta
class UIContextMenuInteraction
An interaction object that you use to display relevant actions for your content.
class UITargetedPreview
An object describing the view to use during preview-related animations.
class UIPreviewTarget
An object that specifies the container view to use for animations.
class UIPreviewParameters
Additional parameters to use when animating a preview interface.
https://developer.apple.com/documentation/uikit/uimenusystem/main
- UIKit
- UIMenuSystem
- main
Type Property
main
The main menu system.
@MainActor class var main: UIMenuSystem { get }
Discussion
In Mac apps built with Mac Catalyst, the main menu system is the app’s menu bar.
See Also
Getting a menu system
class var context: UIMenuSystem
The context menu system.
https://developer.apple.com/documentation/uikit/uiresponder/buildmenu(with:)
#app-main)
- UIKit
- UIResponder
- buildMenu(with:)
Instance Method
buildMenu(with:)
Asks the receiving responder to add and remove items from a menu system.
@MainActor func buildMenu(with builder: any UIMenuBuilder)
Parameters
builder
An object that you use to modify a menu system for your app.
Discussion
Override this method in your app delegate or view controller to receive a UIMenuBuilder object. Use the builder to add and remove UIMenuElement objects such as UIMenu, UIAction, and UICommand from your app’s menu bar or context menus.
Where you override this method determines the menu system that the builder updates. To add and remove items from the menu bar using the main menu system, override buildMenu(with:) in your app delegate. To build a context menu using the context system, override this method in your view controller.
See Also
Building and validating commands
func validate(UICommand)
Asks the receiving responder to validate the command.
Requests the receiving responder to enable or disable the specified command in the user interface.
Returns the target object that responds to an action.
https://developer.apple.com/documentation/uikit/uimenubuilder
- UIKit
- UIMenuBuilder
Protocol
UIMenuBuilder
An interface for adding and removing menus from a menu system.
@MainActor protocol UIMenuBuilder
Mentioned in
Optimizing your iPad app for Mac
Overview
You don’t create a menu builder object. Instead, you override buildMenu(with:) in your app delegate or view controller to receive a builder object. Where you override this method determines the system that the builder updates. To add and remove menus from the menu bar using the main menu system, override buildMenu(with:) in your app delegate. To build a context menu using the context system, override the method in your view controller.
To see an example of how to use a menu builder object, see Adding menus and shortcuts to the menu bar and user interface.
Topics
Getting menu systems and elements
var system: UIMenuSystem
The menu system that the menu builder modifies.
Required
Gets the menu for the specified menu identifier.
Gets the action for the specified action identifier.
Gets the command for the specified selector and property list.
Inserting child menus
func insertChild(UIMenu, atStartOfMenu: UIMenu.Identifier)
Adds a child menu as the first element of the specified parent menu.
func insertChild(UIMenu, atEndOfMenu: UIMenu.Identifier)
Adds a child menu as the last element of the specified parent menu.
Inserting sibling menus
func insertSibling(UIMenu, beforeMenu: UIMenu.Identifier)
Inserts a sibling menu before the specified menu.
func insertSibling(UIMenu, afterMenu: UIMenu.Identifier)
Inserts a sibling menu after the specified menu.
Replacing menus and child menu elements
Replaces the elements in a menu with the elements returned by the specified handler block.
Removing a menu
func remove(menu: UIMenu.Identifier)
Removes a menu from the menu system.
Instance Methods
func insertElements([UIMenuElement], afterAction: UIAction.Identifier)
Insert elements after an identified action.
Beta
func insertElements([UIMenuElement], afterCommand: Selector, propertyList: Any?)
func insertElements([UIMenuElement], afterMenu: UIMenu.Identifier)
Insert elements after an identified menu.
func insertElements([UIMenuElement], atEndOfMenu: UIMenu.Identifier)
Insert elements at the end of an identified parent menu.
func insertElements([UIMenuElement], atStartOfMenu: UIMenu.Identifier)
Insert elements at the start of an identified parent menu.
func insertElements([UIMenuElement], beforeAction: UIAction.Identifier)
Insert elements before an identified action.
func insertElements([UIMenuElement], beforeCommand: Selector, propertyList: Any?)
func insertElements([UIMenuElement], beforeMenu: UIMenu.Identifier)
Insert elements before an identified menu.
func remove(action: UIAction.Identifier)
Remove an identified action.
func remove(command: Selector, propertyList: Any?)
func replace(action: UIAction.Identifier, with: [UIMenuElement])
Replace an identified action with menu elements.
func replace(command: Selector, propertyList: Any?, with: [UIMenuElement])
func replace(menu: UIMenu.Identifier, with: [UIMenuElement])
Replace an identified menu with menu elements.
func replace(menu: UIMenu.Identifier, with: UIMenu)
Replace an identified menu with a menu.
See Also
App menus
class UIMenu
A container for grouping related menu elements in an app menu or contextual menu.
class UIMenuSystem
An object representing a main or contextual menu system.
class UIMainMenuSystem
The main menu system.
https://developer.apple.com/documentation/uikit/uiaction
- UIKit
- UIAction
Class
UIAction
A menu element that performs its action in a closure.
@MainActor class UIAction
Overview
Create a UIAction object when you want a menu element that performs its action in a closure. The following example adds an action-based menu to the File menu:
// Create a closure-based action to use as a menu element. let refreshAction = UIAction(title: "Refresh") { (action) in print("Refresh the data.") }
// Use the .displayInline option to avoid displaying the menu as a submenu, // and to separate it from the other menu elements using a line separator. let refreshMenuItem = UIMenu(title: "", options: .displayInline, children: [refreshAction])
// Insert the menu into the File menu before the Close menu. builder.insertSibling(refreshMenuItem, beforeMenu: .close)
Topics
Creating an action
convenience init(title: String, subtitle: String?, image: UIImage?, identifier: UIAction.Identifier?, discoverabilityTitle: String?, attributes: UIMenuElement.Attributes, state: UIMenuElement.State, handler: UIActionHandler)
Creates an action with the specified title, subtitle, image, identifier, discoverability title, attributes, state, and handler.
convenience init(title: String, image: UIImage?, identifier: UIAction.Identifier?, discoverabilityTitle: String?, attributes: UIMenuElement.Attributes, state: UIMenuElement.State, handler: UIActionHandler)
Creates an action with the specified title, image, identifier, discoverability title, attributes, state, and handler.
Creates an action for capturing text using the device’s camera.
struct Identifier
A type that represents an action identifier.
typealias UIActionHandler
A type that defines the closure for an action handler.
Getting information about the action
var title: String
The action’s title.
var image: UIImage?
The action’s image.
var identifier: UIAction.Identifier
The unique identifier for the action.
var discoverabilityTitle: String?
An elaborated title that explains the purpose of the action.
var attributes: UIMenuElement.Attributes
The attributes indicating the style of the action.
var state: UIMenuElement.State
The state of the action.
var sender: Any?
The object responsible for the action handler.
Initializers
convenience init(title: String, subtitle: String?, image: UIImage?, selectedImage: UIImage?, identifier: UIAction.Identifier?, discoverabilityTitle: String?, attributes: UIMenuElement.Attributes, state: UIMenuElement.State, handler: UIActionHandler)
Relationships
Inherits From
UIMenuElement
Inherited By
UIWindowScene.ActivationAction
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSCopyingNSObjectProtocolNSSecureCodingSendableSendableMetatypeUIAccessibilityIdentificationUIMenuLeaf
See Also
Menu elements and keyboard shortcuts
Adding menus and shortcuts to the menu bar and user interface
Provide quick access to useful actions by adding menus and keyboard shortcuts to your Mac app built with Mac Catalyst.
Adopting menus and UIActions in your user interface
Add menus to your user interface, with built-in button support and bar-button items, and create custom menu experiences.
class UIMenuElement
An object representing a menu, action, or command.
class UICommand
A menu element that performs its action in a selector.
class UIKeyCommand
An object that specifies a key press perform on a hardware keyboard and the resulting action.
class UIDeferredMenuElement
A placeholder menu element that the system replaces with the result of the block’s completion handler.
class Provider Beta
struct Attributes
Attributes that determine the style of the menu element.
enum State
Constants that indicate the state of an action- or command-based menu element.
protocol UIMenuLeaf
An interface for an object that represents a menu element without child elements.
https://developer.apple.com/documentation/uikit/uikeycommand
- UIKit
- UIKeyCommand
Class
UIKeyCommand
An object that specifies a key press perform on a hardware keyboard and the resulting action.
tvOS
@MainActor class UIKeyCommand
Mentioned in
Choosing a user interface idiom for your Mac app
Overview
Hardware keyboards allow a user to hold down the Control, Option, Command, or other modifier key and press another key in combination to initiate commands such as Cut, Copy, or Paste. You can use instances of this class to define custom command sequences that your app recognizes and then provide an appropriate response.
To use this class, you create instances and associate them with your app’s responder objects. Each responder has a keyCommands property that you can redefine and use to return the key command objects that responder supports. Key command sequences are generated only for devices with an attached hardware keyboard.
The system always has the first opportunity to handle key commands. Key commands that map to known system events (such as Cut, Copy, and Paste) are automatically routed to the appropriate responder methods. For other key commands, the system looks for an object in the responder chain with a key command object that matches the pressed keys. If it finds such an object, it then searches the responder chain, looking for the first object that implements the corresponding action method, and calls the first one it finds.
iPad apps that run in macOS can use UIKeyCommand to create menu elements that have keyboard shortcuts.
Topics
Creating a key command object
Creates a key command that you can use as a menu element with a shortcut key, or a shortcut key only for a view controller.
convenience init(input: String, modifierFlags: UIKeyModifierFlags, action: Selector)
Creates a key command that matches the specified input.
init?(coder: NSCoder)
Creates a key command from data in an unarchiver.
init()
Creates a key command.
Adding menus and shortcuts to the menu bar and user interface
Provide quick access to useful actions by adding menus and keyboard shortcuts to your Mac app built with Mac Catalyst.
Navigating an app’s user interface using a keyboard
Navigate between user interface elements using a keyboard and focusable UI elements in iPad apps and apps built with Mac Catalyst.
Getting information about the key command
var title: String
The key command’s title.
var image: UIImage?
The key command’s image.
var input: String?
The string of characters corresponding to the keys that must be pressed to match this key command.
var action: Selector?
The command’s action-method selector.
var modifierFlags: UIKeyModifierFlags
The bit mask of modifier flags that must be pressed to match this key command.
struct UIKeyModifierFlags
Constants that indicate which modifier keys are pressed.
var discoverabilityTitle: String?
An elaborated title that explains the purpose of the key command.
var attributes: UIMenuElement.Attributes
The attributes indicating the style of the key command.
var state: UIMenuElement.State
The state of the key command.
Getting command alternatives
var alternates: [UICommandAlternate]
An array of alternative actions to take for the key command.
class UICommandAlternate
An object representing an alternative action for a command.
Localizing keyboard shortcuts
var allowsAutomaticLocalization: Bool
A Boolean value that determines whether the system automatically remaps keyboard shortcuts based on the keyboard layout.
var allowsAutomaticMirroring: Bool
A Boolean value that determines whether the system automatically swaps input strings for some keyboard shortcuts when the interface direction changes.
Overriding the key event delivery behavior
var wantsPriorityOverSystemBehavior: Bool
A Boolean value that indicates whether the key command takes precedence over text input or focus movements.
Associating data
var propertyList: Any?
An object that contains data to associate with the key command.
let UICommandTagShare: String
A value that identifies a command as a Share menu.
Converting strings to key commands
Constants that represent the text input strings that correspond to special nonvisible keys.
Deprecated
convenience init(input: String, modifierFlags: UIKeyModifierFlags, action: Selector, discoverabilityTitle: String)
Creates a key command object that matches the specified input and has a title.
Deprecated
Relationships
Inherits From
UICommand
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCodingNSCopyingNSObjectProtocolNSSecureCodingSendableSendableMetatypeUIAccessibilityIdentificationUIMenuLeaf
See Also
Menu elements and keyboard shortcuts
Adopting menus and UIActions in your user interface
Add menus to your user interface, with built-in button support and bar-button items, and create custom menu experiences.
class UIMenuElement
An object representing a menu, action, or command.
class UIAction
A menu element that performs its action in a closure.
class UICommand
A menu element that performs its action in a selector.
class UIDeferredMenuElement
A placeholder menu element that the system replaces with the result of the block’s completion handler.
class Provider Beta
struct Attributes
Attributes that determine the style of the menu element.
enum State
Constants that indicate the state of an action- or command-based menu element.
protocol UIMenuLeaf
An interface for an object that represents a menu element without child elements.
https://developer.apple.com/documentation/uikit/uicontextmenuinteractiondelegate/contextmenuinteraction(_:previewforhighlightingmenuwithconfiguration:)
#app-main)
- UIKit
- UIContextMenuInteractionDelegate
- contextMenuInteraction(_:previewForHighlightingMenuWithConfiguration:) Deprecated
Instance Method
contextMenuInteraction(_:previewForHighlightingMenuWithConfiguration:)
Returns the source view to use when animating the appearance of the preview interface.
iOS 13.0–16.0DeprecatediPadOS 13.0–16.0DeprecatedMac Catalyst 13.1–16.0DeprecatedvisionOS 1.0–1.0Deprecated
@MainActor optional func contextMenuInteraction( _ interaction: UIContextMenuInteraction, previewForHighlightingMenuWithConfiguration configuration: UIContextMenuConfiguration
Parameters
interaction
The interaction object that triggered the preview.
configuration
The configuration object associated with the current interaction.
Return Value
An object containing the source view and configuration parameters for the animation.
Discussion
UIKit calls this method before an interaction begins, to give you an opportunity to supply a custom source view for the presentation animations. If you didn’t provide a preview handler block in the configuration data, UIKit displays the specified view in the preview interface.
See Also
Deprecated
Returns the destination view to use when animating the appearance of the preview interface.
Deprecated
https://developer.apple.com/documentation/uikit/uiresponder/validate(_:)
#app-main)
- UIKit
- UIResponder
- validate(_:)
Instance Method
validate(_:)
Asks the receiving responder to validate the command.
@MainActor func validate(_ command: UICommand)
Parameters
command
A mutable command object.
Discussion
Override this method in your view controller to make changes to a command before the command system renders it as a menu item.
See Also
Building and validating commands
func buildMenu(with: any UIMenuBuilder)
Asks the receiving responder to add and remove items from a menu system.
Requests the receiving responder to enable or disable the specified command in the user interface.
Returns the target object that responds to an action.
https://developer.apple.com/documentation/uikit/uimenusystem)
https://developer.apple.com/documentation/uikit/uicontextmenuinteractiondelegate).
https://developer.apple.com/documentation/uikit/uimenusystem/main)
https://developer.apple.com/documentation/uikit/uiresponder/buildmenu(with:))
https://developer.apple.com/documentation/uikit/uimenubuilder)
https://developer.apple.com/documentation/uikit/uiaction)
https://developer.apple.com/documentation/uikit/uikeycommand).
https://developer.apple.com/documentation/uikit/uicontextmenuinteractiondelegate/contextmenuinteraction(_:previewforhighlightingmenuwithconfiguration:)).
).#app-main)
The page you're looking for can't be found.
Search developer.apple.comSearch Icon
https://developer.apple.com/documentation/uikit/uiresponder/validate(_:)),
https://developer.apple.com/documentation/uikit/nsuiviewtoolbaritem
- UIKit
- NSUIViewToolbarItem
Class
NSUIViewToolbarItem
An item in a window’s toolbar that hosts a custom UIKit view.
@MainActor class NSUIViewToolbarItem
Mentioned in
Building a desktop-class iPad app
Overview
The NSUIViewToolbarItem class lets you display a UIView in an NSToolbar. Use this class if you have a custom UIKit view you want to appear as a control in a toolbar when you build your app with Mac Catalyst.
For UIKit controls that support behavioral styles, set preferredBehavioralStyle to UIBehavioralStyle.mac if you want them to appear in the toolbar with the appearance and behavior of AppKit controls.
Topics
Creating a toolbar item
init(itemIdentifier: NSToolbarItem.Identifier, uiView: UIView)
Creates a toolbar item with the identifier and underlying UIKit view you specify.
Managing the view
var uiView: UIView
The UIKit view to host in an AppKit toolbar.
Relationships
Inherits From
NSToolbarItem
Conforms To
CVarArgCustomDebugStringConvertibleCustomStringConvertibleEquatableHashableNSCopyingNSObjectProtocolUIPopoverPresentationControllerSourceItem
See Also
Items
@MainActor class NSToolbarItem
A single item that appears in a window’s toolbar.
@MainActor class NSToolbarItemGroup
A group of subitems in a toolbar item.
enum ControlRepresentation
enum SelectionMode
A value that indicates how a grouped toolbar item selects its subitems.
@MainActor class NSMenuToolbarItem
A control that presents a menu in a window’s toolbar.
@MainActor class NSSearchToolbarItem
A toolbar item that contains a search field optimized for performing text-based searches.
@MainActor class NSTrackingSeparatorToolbarItem
A toolbar separator that aligns with the vertical split view in the same window.
https://developer.apple.com/documentation/uikit/nsuiviewtoolbaritem)
https://developer.apple.com/documentation/uikit/uititlebar/titlevisibility
- UIKit
- UITitlebar
- titleVisibility
Instance Property
titleVisibility
A value that indicates the visibility of the title.
@MainActor var titleVisibility: UITitlebarTitleVisibility { get set }
Mentioned in
Removing the title bar in your Mac app built with Mac Catalyst
Discussion
Setting the title visibility to UITitlebarTitleVisibility.hidden hides only the title displayed in the title bar, not the title bar itself. To remove the title bar from the window, set titleVisibility to UITitlebarTitleVisibility.hidden and toolbar to nil.
This property defaults to UITitlebarTitleVisibility.visible.
See Also
Configuring the title bar
var separatorStyle: UITitlebarSeparatorStyle
The type of separator that the app displays between the title bar and content of a window.
enum UITitlebarSeparatorStyle
Styles that determine the type of separator displayed between the title bar and content of a window.
enum UITitlebarTitleVisibility
States that determine visibility of the title in the title bar.
var representedURL: URL?
A URL of the file or resource represented in the window.
https://developer.apple.com/documentation/uikit/uititlebartitlevisibility/hidden
- UIKit
- UITitlebarTitleVisibility
- UITitlebarTitleVisibility.hidden
Case
UITitlebarTitleVisibility.hidden
A state indicating that the title isn’t visible in the title bar.
case hidden
Mentioned in
Removing the title bar in your Mac app built with Mac Catalyst
See Also
Visibility states
case visible
A state indicating that the title is visible in the title bar.
https://developer.apple.com/documentation/uikit/uititlebar/toolbar
- UIKit
- UITitlebar
- toolbar
Instance Property
toolbar
The toolbar displayed beneath or integrated with the title bar.
@MainActor var toolbar: NSToolbar? { get set }
Mentioned in
Removing the title bar in your Mac app built with Mac Catalyst
See Also
Configuring the toolbar
var toolbarStyle: UITitlebarToolbarStyle
The style of the toolbar determining its appearance and location related to the title bar.
enum UITitlebarToolbarStyle
Styles that determine the toolbar’s appearance and location related to the title bar.
var autoHidesToolbarInFullScreen: Bool
A Boolean value that determines whether the toolbar automatically hides in full-screen windows.
https://developer.apple.com/documentation/uikit/uititlebar/titlevisibility)
https://developer.apple.com/documentation/uikit/uititlebartitlevisibility/hidden)
https://developer.apple.com/documentation/uikit/uititlebar/toolbar)
https://developer.apple.com/documentation/uikit/uitooltipinteraction/delegate
- UIKit
- UIToolTipInteraction
- delegate
Instance Property
delegate
An object that provides text that a tooltip displays instead of the default text.
@MainActor weak var delegate: (any UIToolTipInteractionDelegate)? { get set }
Discussion
To provide tooltip text based on the current state or unique logic of your app, set the delegate property to an object that conforms to the UIToolTipInteractionDelegate protocol and implements the toolTipInteraction(_:configurationAt:) method. The method returns a UIToolTipConfiguration object containing the text to display in the tooltip. For example, the following code listing instructs the tooltip to show the name of the view’s background color instead of the defaultToolTip text. If the color name is unavailable, the method returns nil, which disables the display of the tooltip.
let configuration: UIToolTipConfiguration? if let accessibilityName = backgroundColor?.accessibilityName { configuration = UIToolTipConfiguration(toolTip: "The color is (accessibilityName).") } else { configuration = nil }
return configuration }
See Also
Providing tooltip configurations
protocol UIToolTipInteractionDelegate
An interface that provides tooltip settings to an interaction.
https://developer.apple.com/documentation/uikit/uicontrol/tooltip
- UIKit
- UIControl
- toolTip
Instance Property
toolTip
The default text to display in the control’s tooltip.
@MainActor var toolTip: String? { get set }
Discussion
Set this property to the text that should appear in the tooltip. If you want your app to determine the tooltip text at a later time — for instance, to determine the text based on the current state of your app — set the delegate property of toolTipInteraction after setting toolTip with the default text. For example, the following code listing sets the tooltip’s default text and delegate for a shopping cart button:
let button = UIButton(configuration: configuration, primaryAction: action) button.toolTip = "Click to add the item to your cart. Your cart is empty." button.toolTipInteraction?.delegate = self
If the delegate implements the method toolTipInteraction(_:configurationAt:), the tooltip ignores the default text set in the toolTip property. For more information, see toolTipInteraction.
See Also
Showing tooltips
var toolTipInteraction: UIToolTipInteraction?
The tooltip interaction associated with the control.
https://developer.apple.com/documentation/uikit/uicontrol/tooltipinteraction
- UIKit
- UIControl
- toolTipInteraction
Instance Property
toolTipInteraction
The tooltip interaction associated with the control.
@MainActor var toolTipInteraction: UIToolTipInteraction? { get }
Discussion
When you set the toolTip property, the control creates a UIToolTipInteraction object and assigns it to the toolTipInteraction property.
If you want to change the text of the tooltip based the current state of your app or application logic, assign a UIToolTipInteractionDelegate object to toolTipInteraction‘s delegate property. For example, the following code listing sets the tooltip’s default text and delegate for a shopping cart button:
lazy var shoppingCartButtonWithTooltip: UIButton = { var configuration = UIButton.Configuration.filled() configuration.title = "Add to Cart" configuration.image = UIImage(systemName: "cart", variant: .circle) configuration.imagePlacement = NSDirectionalRectEdge.leading configuration.imagePadding = 4
let action = UIAction { [unowned self] _ in self.cartItemCount += 1 }
let button = UIButton(configuration: configuration, primaryAction: action) button.toolTip = "Click to add the item to your cart. Your cart is empty." button.toolTipInteraction?.delegate = self
return button }()
Then the delegate returns a tooltip configuration containing text that states the number of items in the shopping cart by implementing the toolTipInteraction(_:configurationAt:) method:
let text: String switch cartItemCount { case 0: text = "Click to add the item to your cart. Your cart is empty." case 1: text = "Click to add the item to your cart. Your cart contains (cartItemCount) item." default: text = "Click to add the item to your cart. Your cart contains (cartItemCount) items." }
return UIToolTipConfiguration(toolTip: text) }
See Also
Showing tooltips
var toolTip: String?
The default text to display in the control’s tooltip.
https://developer.apple.com/documentation/uikit/uitooltipinteraction/init()
#app-main)
- UIKit
- UIToolTipInteraction
- init()
Initializer
init()
Creates a tooltip interaction object.
@MainActor init()
Return Value
A tooltip interaction object.
See Also
Creating a tooltip interaction
init(defaultToolTip: String)
Creates a tooltip interaction object and sets the default tooltip text.
https://developer.apple.com/documentation/uikit/uitooltipinteraction/init(defaulttooltip:)
#app-main)
- UIKit
- UIToolTipInteraction
- init(defaultToolTip:)
Initializer
init(defaultToolTip:)
Creates a tooltip interaction object and sets the default tooltip text.
@MainActor init(defaultToolTip: String)
Parameters
defaultToolTip
The text that appears in the tooltip by default.
Return Value
A tooltip interaction object.
See Also
Creating a tooltip interaction
init()
Creates a tooltip interaction object.
https://developer.apple.com/documentation/uikit/uitooltipinteraction/isenabled
- UIKit
- UIToolTipInteraction
- isEnabled
Instance Property
isEnabled
A Boolean value that indicates whether the tooltip interaction is in the enabled state.
@MainActor var isEnabled: Bool { get set }
Discussion
A view or control can only display a tooltip from an enabled interaction. Set the value of the isEnabled property to true to enable the interaction or false to disable it. The default value is true.
See Also
Managing the interaction
var defaultToolTip: String?
The text that appears in a tooltip by default.
https://developer.apple.com/documentation/uikit/uitooltipinteraction/defaulttooltip
- UIKit
- UIToolTipInteraction
- defaultToolTip
Instance Property
defaultToolTip
The text that appears in a tooltip by default.
@MainActor var defaultToolTip: String? { get set }
Discussion
Set this property to the default text to display in the tooltip.
If you set the delegate property to an object that conforms to the UIToolTipInteractionDelegate protocol and implements the toolTipInteraction(_:configurationAt:) method, then the return value of the delegate method determines the text that appears in the tooltip.
See Also
Managing the interaction
var isEnabled: Bool
A Boolean value that indicates whether the tooltip interaction is in the enabled state.
