UIKit - free Swift example code
About 49 min
UIKit - free Swift example code 관련
UIKit - free Swift example code
Learn Swift coding for iOS with these free tutorials – learn Swift, iOS, and Xcode
Found 176 articles in the Swift Knowledge Base for this category.
Changing which UITabBarController tabs can be edited
If you have a More tab in your tab bar controller, this will automatically get an Edit button so that users can drag tabs around to customize the user interface. This doesn't actually save the tab ordering for you, which means the tabs will revert on next run unless you persist the user's choices yourself, but it does do everything else for you....
Fixing ”Failed to obtain a cell from its DataSource”
This is a common error, but it's easily fixed. There are two main reasons why table views fail to return cells, but they give different error messages. If you get an error like this:...
Fixing ”Unable to dequeue a cell with identifier”
This error usually means there's a problem with your cell prototypes. There are two main reasons why table views fail to return cells, but they give different error messages. If you get an error like this:...
How do you show a modal view controller when a UITabBarController tab is tapped?
Usually tapping a tab in a
UITabBar
shows that tab, but it's often the case that you want to override that behavior, for example to show a view modally. If you're using one of Xcode's built-in storyboard templates for creating your user interface, it's not immediately obvious how to do this, but fortunately it's not so hard using the approach below....How set different widths for a UISegmentedControl's elements
Segmented controls give each segment equal width by default, which is aesthetically pleasing when you have space to spare but technically irritating when space is tight. Rather than try to squash too much into a small space, you have two options: set custom segment widths, or ask iOS to size them individually for you....
How to activate multiple Auto Layout constraints using activate()
Using Auto Layout is the best way to create complex layouts that automatically adapt to their environment, but sometimes adding and removing lots of constraints can cause performance
How to add a badge to your UITabBarItem
You can put a badge over any of your tab bar items, and doing so is a great way to encourage users to activate the tab to see what information you want to show them....
How to add a bar button to a navigation bar
Navigation bars are one of the most common user interface components in iOS, so being able to add buttons to them is something you'll do a lot. You can add buttons to the left and right side of a navigation bar, and you can add more than one to either side....
How to add a button to a navigation bar using storyboards
Once you’ve placed a view controller inside a navigation controller, you’ll see that Interface Builder simulates a navigation bar at the top of that view controller. If you select it, what you actually select is the navigation item for that controller – the same thing you would get if you were manipulating its
navigationItem
property....How to add a button to a UITableViewCell
There are two steps to add a working button to a table view cell. The first step is to add a button like this:...
How to add a custom view to a UIBarButtonItem
Most
UIBarButtonItems
contain either an icon or some text, but they can do so much more – in fact, you can embed any kind of UIView
subclass inside a bar button item, then put that button into a navigation bar or toolbar as you normally would....How to add a flexible space to a UIBarButtonItem
There's a special kind of
UIBarButtonItem
called flexibleSpace
, and this acts like a spring between other buttons, pushing them to one side. A flexible space will always expand to take up as much room as possible, splitting space evenly between other flexible spaces if they exist....How to add a number over your app icon using applicationIconBadgeNumber
Once your app has the user’s permission to do so, you can show numbers over your icon to indicate outstanding tasks, unread messages, game invites, or whatever makes sense for your app....
How to add a section header to a table view
You can use the built-in iOS table section headers by returning a value from
titleForHeaderInSection
like this:...How to add a shadow to a UIView
iOS can dynamically generate shadows for any
UIView
, and these shadows automatically adjust to fit the shape of the item in question – even following the curves of text inside a UILabel
. This functionality is built right in, so all you need to do is configure its properties, and there are four you need to care about:...How to add a toolbar above the keyboard using inputAccessoryView
If your user is likely to want common editing operations to appear while they are typing, you should set a custom view for your text fields’
inputAccessoryView
property. For example, Tweetbot shows common Twitter symbols right above the keyboard, such as @
and #
, so you can type them without having to adjust the iOS keyboard....How to add a UIApplicationShortcutItem quick action for 3D Touch
There are two ways to add a shortcut item for 3D Touch: you can register a list of static items that always get shown, or you can create a dynamic list in code based on user information....
How to add a UITextField to a UIAlertController
The
UIAlertController
class from iOS 8.0 lets you add as many text fields as you need, and you can read the value of those text fields when the user taps a button....How to add blur and vibrancy using UIVisualEffectView
As of iOS 8.0, visual effects such as blur and vibrancy are a cinch because Apple provides a built in
UIView
subclass that does all the hard work: UIVisualEffectView
. For example, if you want to blur an image, you would use this code:...How to add custom spacing to UIStackView items
Each
UIStackView
has an overall spacing
property that affects spacing between all of its arranged subviews, but in addition you can add custom spacing after specific views – for example, “put 20 points of space under this button.”...How to add drag and drop to your app
Drag and drop is a feature that’s hugely useful, so don’t be surprised if your users email you asking for it to be added. Even though both
UITableView
and UICollectionView
both have support for drag and drop, it still takes a fair amount of work to set up....How to add multiple UIBarButtonItem to a navigation bar using rightBarButtonItems
The
navigationItem
property of your view controller has two properties responsible for displaying multiple bar button items on either side of UINavigationBar
: leftBarButtonItems
for the left-hand side and rightBarButtonItems
for the right-hand side. These are not to be confused with leftBarButtonItem
and rightBarButtonItem
, which are older properties designed to store single items....How to add peek and pop to a UITableView
Peek and pop are features of 3D Touch that let users press hard on something to show more information. It’s surprisingly easy to add when working with table view cells and collection view cells, and downright trivial if you use storyboards and segues....
How to add Retina and Retina HD graphics to your project
iOS has a simple, beautiful solution for handling Retina and Retina HD graphics, and in fact it does almost all the work for you – all you have to do is name your assets correctly....
How to add scopes to a UISearchController
By default a
UISearchController
provides just a text input field, but with a few small changes you can make it add scopes buttons underneath to let the user control how their search happens....How to adjust a UIScrollView to fit the keyboard
If your user interface brings up the keyboard, you should respond by adjusting your layout so that all parts are still visible. If you're using a
UIScrollView
or any classes that have a scroll view as part of their layout (table views and text views, for example), this means adjusting the contentInset
property to account for the keyboard....How to adjust image content mode using aspect fill, aspect fit and scaling
All views (including those that don't hold images) have a content mode that affects the way they draw their content. The default is
Scale To Fill
because it's fastest: the contents of the view just get stretched up (or down) to fit the space available. But there are two others that you'll be using a lot: Aspect Fit and Aspect Fill....How to animate a blur effect using UIVisualEffectView
UIKit’s
UIVisualEffectView
class lets us add blurring effects to any view, optionally also combining a vibrancy effect to overlaid controls to help make them stand out. This makes it perfect for partly obscuring background content when you want to present information on top, and you can even animate that presentation if you want....How to animate views using animate(withDuration:)
Animation in iOS is done by starting an animation block, then telling iOS what changes you want to make. Because the animation block is active, those changes won't happen straight away – instead, iOS will execute them smoothly over the time you specified, so you don't have to worry when it will finish or what all the intermediate states are....
How to animate views using UIViewPropertyAnimator
iOS 10 introduced a new closure-based animation class in the form of
UIViewPropertyAnimator
. Amongst other things, it lets you interactively adjust the position of an animation, making it jump to any point in time that we need – a technique commonly called scrubbing. ...How to animate views with spring damping using animate(withDuration:)
Spring animations work by changing from a start state to an end state, with a slight overshoot and bounce at the end. For example, if you want to animate a view moving from X:0 to X:100, it might move to X:120 before bouncing back to X:80, then X:110 and finally X:100, as if the animation were attached to a spring....
How to animate when your size class changes: willTransition(to:)
A size class change is usually triggered by your user rotating their device, but it can also happen for example when using the new iOS 9.0 multitasking to adjust window splits. Your UI needs to look great in all size classes it supports, which means you either create multiple variations of your layouts inside Interface Builder (this is the preferred route) or you make changes in code....
How to ask users to review your app using SKStoreReviewController
Many apps ask users to review their apps, but it’s increasingly common to see dark patterns such as apps pre-screening users so they get sent to the App Store only if they said they like the app....
How to bring a subview to the front of a UIView
UIKit draws views back to front, which means that views higher up the stack are drawn on top of those lower down. If you want to bring a subview to the front, there's a method just for you:
bringSubviewToFront()
. Here's an example:...How to center a view in its container
There are two ways to center one
UIView
inside another, depending on whether you use Auto Layout....How to change the scroll indicator inset for a UIScrollView
It's common to adjust content insets of a scroll view or any class that embeds one (table view, text view, etc) so that you control the scrolling mechanism precisely, but whenever you change the content inset it's a good idea also to change the scroll indicator inset: the visual indicator bar on the right that shows users how far they have left to scroll....
How to change your app icon dynamically with setAlternateIconName()
iOS gives developers the ability to change their app’s icon programmatically, although it takes a little work to set up. It also isn’t quite as powerful as you might hope – you can’t recreate the moving hands of the Clock app, for example....
How to check a string is spelled correctly using UITextChecker
You can draw on the iOS dictionary in just a few lines of code thanks to the
UITextChecker
class. Tell it the range of the string you want to check (this could be the whole string or just part of it), then ask it to tell you where the spelling error is. If it says there are no errors, the word is good. Here's the code:...How to check whether an iPhone or iPad is upside down or face up
If your app needs to know the orientation of the user’s device – face up or face down – it takes only four steps to implement....
How to check whether users have enabled the reduced motion setting
There’s a lot of animation in UIKit, and many users find it either distracting or hard to follow. As a result, iOS has a Reduce Motion accessibility setting that disables many animation and parallax effects, and simplifies most others – at least in their own apps....
How to control a UIProgressView’s animation
The
UIProgressView
class has a built-in setProgress()
method that adjusts its progress with animation, but by default you don’t have control over the timing of that animation....How to control which screen edges trigger system gestures using preferredScreenEdgesDeferringSystemGestures
iOS 11.0 was the first to showcase complex system gestures based around the iPhone X, and it’s the point now where all edges of the screen do different things on different devices. ...
How to convert a CGPoint in one UIView to another view using convert()
Each view has its own co-ordinate system, meaning that if I tap a button and ask iOS where I tapped, it will tell me where I tapped relative to the top-left of the button. This is usually what you want, but if you want to translate a position in one view into a position it's easy enough to do....
How to create a page curl effect using UIPageViewController
When iBooks first launched in iOS 3.2, its page curl effect was almost addictive: it moved so fluently with your finger that it felt you were touching real paper. From iOS 5.0 on this page curl effect is available for every developer as part of the
UIPageViewController
class. Its API isn't immediately obvious to newbies, though, so I'm going to give you a complete example....How to create a parallax effect in UIKit
Parallax effects have been standard since iOS 7.0, and the
UIInterpolatingMotionEffect
class makes this easy by automatically smoothing accelerometer input so your views can adjust to tilt data....How to create Auto Layout constraints in code: constraints(withVisualFormat:)
While the complexities of Auto Layout make it something most people prefer to grapple with using Interface Builder, it does have some cool tricks up its sleeve if you prefer to work in code. One of those tricks is called Visual Format Language (VFL) and lets you use ASCII art to tell iOS how you want your views laid out....
How to create custom menus using UIMenuController
iOS has a built-in menu system that, while useful, doesn't actually get much use – because users don't expect to see it, developers don't use it, thus making it even less likely that users expect to see it....
How to create custom text input using UIKeyInput
Although we can use
pressesBegan()
and pressesEnded()
to read keypresses, they won’t show the on-screen keyboard and so won’t let you provide custom text input for users without a hardware keyboard. If you need that keyboard to be shown, you should create a class that adopts the UIKeyInput
protocol instead, which has just three requirements:...How to create keyframe animations using animateKeyframes()
If you need to combine a selection of animations over time the easiest thing to do is create a keyframe animation. This starts with a call to
animateKeyframes()
, then you go ahead and call addKeyframe()
as many times as you need....How to create live playgrounds in Xcode
A reader emailed me to say they had enjoyed my books, and were considering applying for a scholarship to WWDC17. The process for this requires creating a live playground, and they were emailing to ask whether I had any tutorials on the process. ...
How to create popover menus using UIPopoverPresentationController
Show a
UIAlertController
action sheet on iPad isn't as easy as on iPhone. The reason for this is simple: on iPhone the action sheet slides up from the bottom, effectively owning the user's attention until it's dismissed, whereas on iPad it could be shown from anywhere. In fact, if you just try and show one on an iPad like this, your app crashes:...How to customize a view controller’s back button on a navigation bar: backBarButtonItem
When you move between view controllers using
UINavigationController
, it automatically configures a Back button show either “Back” or the title of the previous view controller. That usually works well enough, but if your previous controller has a long title you’ll probably want something custom....How to customize swipe edit buttons in a UITableView
As of iOS 8.0 there's an easy way to customize the list of buttons that appear when the user swipes from right to left:
editActionsForRowAt
. Return an array of UITableViewRowAction
objects that have titles and styles (and also background colors if you want to customize their appearance), and iOS does the rest....How to deselect a UITableViewCell using clearsSelectionOnViewWillAppear
When a user taps a table view row, it automatically gets highlighted by iOS, and frequently we use that action to show another view controller with more detailed information. When the user goes back, though, you probably want their selection to go away so that it doesn't remain selected, and if you're using a
UITableViewController
that's easy to do with clearsSelectionOnViewWillAppear
...How to detect a double tap gesture
The iOS
UITapGestureRecognizer
class has a built-in way to detect a double tap on any view. All you need to do is create the recognizer, set its numberOfTapsRequired
property to 2, then add it to the view you want to monitor....How to detect dark mode in iOS
If you need to take specific action depending on whether your user is running in light mode or dark mode – for example, doing some different drawing – then you should query the
userInterfaceStyle
of your view controller’s trait collection....How to detect edge swipes
Detecting pan gestures is easy enough with a regular
UIPanGestureRecognizer
, but there's a special gesture recognizer to use if you want to detect the user swiping from the edge of their screen. The example below demonstrates detecting the user swiping from the left edge of the screen:...How to detect keyboard input using pressesBegan() and pressesEnded()
UIKit lets us detect hardware keyboard input from the user through the methods
pressesBegan()
and pressesEnded()
, both of which are passed a set of UIPress
instances that contain key codes and modifiers we can inspect. If you implement one of these two methods, you should call super
to forward the message on for any keyboard events you don’t handle....How to detect long presses using UILongPressGestureRecognizer
UIKit has a dedicated gesture recognizer that can detect and respond to the user pressing and holding on a view. You can configure how many fingers should be used, whether the user needs to tap the screen first, and how much they are allowed to move their finger before the long press is considered to be a panning movement instead....
How to detect when the Back button is tapped
You probably already know that
viewWillDisappear()
is called when a view controller is about to go away, and that's also called when the user taps the Back button in a navigation controller. Problem is, the same method is called when the user moves forward, i.e. when you push another view controller onto the stack....How to detect when the user takes a screenshot
If you’re showing sensitive data it can be important to know when you’re user takes a screenshot. Snapchat, for example, automatically notifies participants in a conversation if someone takes a screenshot, effectively letting them know their privacy might have been breached....
How to detect when your size class changes
All view controllers have a size class, which is a vague description of how much space is available both horizontally and vertically. These sometimes change when the user rotates their device, but can also change on iPad when they split the screen between two apps in various ways....
How to dim the screen
There is no built-in way to dim the screen unless you're presenting a view controller, at which point iOS dims the background view controller for you....
How to disable interactive swipe to dismiss for view controllers
From iOS 13.0 onwards, whenever you present a
UIViewController
you get a card-like user interface where the new view controller can be dismissed by swiping downwards. While this works great for optional information, it works less well if you require the user to make a choice – if you want to stop the view controller from being dismissed until they have taken some sort of action inside the detail view controller....How to disable undo, redo, copy, and paste gestures using editingInteractionConfiguration
iOS provides built-in gestures for undo, redo, copy, and paste in text views, triggered using a variety of three-finger moves – swiping left and right, or pinching in or out respectively. If you have existing gestures that collide with these, you can disable the system gestures by overriding the
editingInteractionConfiguration
property to return .none
....How to draw custom views in Interface Builder using IBDesignable
You've always been able to have custom views inside your apps, but if you're having a hard time visualizing how they look at design time then you should try
@IBDesignable
: it lets you see exactly how your custom views look inside IB, and if you combine it with @IBInspectable
you can even adjust your view's design there too....How to draw shapes using UIBezierPath
UIBezierPath
is a simple and efficient class for drawing shapes using Swift, which you can then put into CAShapeLayer
, SKShapeNode
, or other places. It comes with various shapes built in, so you can write code like this to create a rounded rectangle or a circle:...How to enable large titles in your navigation bar
iOS 11 introduced a new design for navigation bar titles, allowing developers to enable large titles for view controllers that needed to be particularly prominent....
How to find a touch's location in a view with location(in:)
When the user starts touching an iOS screen,
touchesBegan()
is immediately called with a set of UITouches
. If you want to find where the user touched, you need to take one of those touches then use location(in:)
on it, like this:...How to find a UIView subview using viewWithTag()
If you need a quick way to get hold of a view inside a complicated view hierarchy, you're looking for
viewWithTag()
– give it the tag to find and a view to search from, and this method will search all subviews, and all sub-subviews, and so on, until it finds a view with the matching tag number. The method returns an optional UIView
because it might not find a view with that tag, so unwrap it carefully....How to find an aspect fit image’s size inside an image view
All images have a natural size, which is the number of pixels they are wide and high. All image views also have a size, which is whatever width and height they have once their Auto Layout constraints have been resolved. ...
How to find the view controller responsible for a view
If you need to find the view controller that is responsible for a particular view, the easiest thing to do is walk the responder chain. This chain is built into all iOS apps, and lets you walk from one view up to its parent view, its grandparent view, and so on, until it reaches a view controller. You can even carry on going if you want, up through parent view controllers and ultimately to the app delegate....
How to fix Auto Layout problems
If your Auto Layout code isn’t behaving the way you want, there’s a good chance you’re seeing Xcode spew errors into its log while your user interface is thoroughly broken. There are a few steps you can take that might help, and I want to walk through each of them here....
How to fix the error “Failed to instantiate the default view controller for UIMainStoryboardFile”
This error happens due to a simple mistake in your storyboard, and it’s easy to fix. When your app starts, iOS needs to know precisely which view controller needs to be shown first – known as your default view controller....
How to flip a UIView with a 3D effect: transition(with:)
iOS has a built-in way to transition between views, and you can use this to produce 3D flips in just a few lines of code. Here's a basic example that flips between two views:...
How to force a UIView to redraw: setNeedsDisplay()
All views and subclasses are rendered using the
drawRect()
method, but you should never call that method directly yourself. Instead, it gets called by the system whenever drawing is required, which allows it to to avoid multiple redraws if drawRect()
is called several times in a row....How to force a view controller to use light or dark mode
By default all instances of
UIViewController
are set to automatically adapt their color appearance to match the user’s system preferences, but if you want you can force some or all of your app to use light or dark mode by setting the overrideUserInterfaceStyle
property of your view controller to .light
or .dark
....How to generate haptic feedback with UIFeedbackGenerator
iOS 10 introduced new ways of generating haptic feedback using predefined vibration patterns shared by all apps, thus helping users understand that various types of feedback carry special significance. The core of this functionality is provided by
UIFeedbackGenerator
, but that's just an abstract class – the three classes you really care about are UINotificationFeedbackGenerator
, UIImpactFeedbackGenerator
, and UISelectionFeedbackGenerator
....How to give a UINavigationBar a background image: setBackgroundImage()
You can call
setBackgroundImage()
on any navigation bar, providing an image to use and the bar metrics you want it to affect, and you're done. Bar metrics left you specify what sizes of bars you want to change: should this by all bars, just phone-sized bars, or just phone-sized bars on landscape?...How to give a UIStackView a background color
You can't do this –
UIStackView
is a non-drawing view, meaning that drawRect()
is never called and its background color is ignored. If you desperately want a background color, consider placing the stack view inside another UIView
and giving that view a background color....How to give UITableViewCells a selected color other than gray
Ever since iOS 7.0, table view cells have been gray when tapped, even when you specifically told Interface Builder you wanted them to be blue. Don't worry, though: it's an easy thing to change, as long as you don't mind writing three lines of code. Specifically, you need to add something like this to your
cellForRowAt
method:...How to hide passwords in a UITextField
User text in a
UITextField
is visible by default, but you can enable the iOS text-hiding password functionality just by setting your text field's isSecureTextEntry
property to be true, like this:...How to hide the home indicator on iPhone X
iPhone X did away with the home button for the first time in any iPhone, replacing it with an interactive line that sits at the bottom of the screen called the home indicator....
How to hide the navigation bar using hidesBarsOnSwipe
iOS gives
UINavigationController
a simple property that masks some complex behavior. If you set hidesBarsOnSwipe
to be true for any UINavigationController
, then iOS automatically adds a tap gesture recognizer to your view to handle hiding (and showing) the navigation bar as needed. This means you can mimic Safari's navigation bar behavior in just one line of code, like this:...How to hide the navigation bar using hidesBarsOnTap
As of iOS 8.0 it's easy to make a navigation bar automatically hide when the user taps the screen, but only when it's part of a
UINavigationController
. When set to true
, the hidesBarsOnTap
property of a navigation controller automatically adds a tap gesture recognizer to your view to handle hiding (and showing) the navigation bar as needed....How to hide the status bar
You can hide the status bar in any or all of your view controllers just by adding this code:...
How to hide the tab bar when a view controller is shown
If you’re using
UITabBarController
to display a tab strip at the bottom of your user interface, the default behavior for iOS is to display the tabs at all times – even if the user has navigated deep into a UINavigationController
in one of the tabs....How to hide your navigation bar when the keyboard shows: hidesBarsWhenKeyboardAppears
Showing the keyboard on an iPhone dramatically reduces how much space you have available, which is particularly annoying if the user is trying to type into a multi-line text view....
How to identify your Auto Layout constraints
Auto Layout constraints a powerful way of expressing your layouts, but when they go wrong they can be hard to debug. Fortunately, all constraints have a built-in
identifier
property that you can use to identify them uniquely....How to let users choose a font with UIFontPickerViewController
UIKit provides
UIFontPickerViewController
as a built-in view controller for letting users select from a list of installed fonts available for our apps. Using it takes three steps: create a delegate to handle callbacks, create and show an instance of the font picker, then read the response as appropriate....How to let users tap on a UITableViewCell while editing is enabled
As soon as you set the
editing
property of a UITableView
to be true, its cells stop being tappable. This is often a good idea, because if a user explicitly enabled editing mode they probably want to delete or move stuff, and it's only going to be annoying if they can select rows by accident....How to limit the number of characters in a UITextField or UITextView
If you have a
UITextField
or UITextView
and want to stop users typing in more than a certain number of letters, you need to set yourself as the delegate for the control then implement either shouldChangeCharactersIn
(for text fields) or shouldChangeTextIn
(for text views)....How to load a HTML string into a WKWebView or UIWebView: loadHTMLString()
If you want to generate HTML locally and show it inside your app, it's easy to do in both
UIWebView
and WKWebView
. First, here's the code for UIWebView
:...How to load a remote image URL into UIImageView
UIImageView
is designed to load only local images, but with a little work you can make it load remote images too. To get a basic solution, add an extension to UIImageView
that downloads image data using a GCD background thread, then converts that to a UIImage
, and loads it back into the image view on the main thread:...How to localize your iOS app
Localizing an app – i.e. making it display its user interface in other languages – is surprisingly painless in iOS, and really the only hard part is making sure you get all your text translated by native speakers of your target languages....
How to lock a view controller’s orientation using supportedInterfaceOrientations
At the project level you can configure which orientations your whole app should support, but sometimes you want individual view controllers to support a subset of those. For example, you might want most of your app to work in any orientation, but one part to work specifically in portrait....
How to make a background image run under the safe area
Broadly speaking it’s important to place your views so they are inside the safe area layout guide, but there are some occasions when you want to ignore that and have some that run under the safe area. Apple’s Weather app, for example, goes edge to edge with background weather graphics, then places the important content inside the safe area....
How to make a button glow when tapped with showsTouchWhenHighlighted
If you want an easy way to let users know when a
UIButton
was tapped, try setting its showsTouchWhenHighlighted
property to be true. This will render a circular glow effect behind the button when it's tapped, which is particularly effective on text-only buttons....How to make a clear button appear in a textfield
If you want to let users clear their entry on a
UITextField
, the standard approach is to add a clear button to the right edge of the text field. This can be done in two ways, depending on what effect you want:...How to make a UIView fill the screen using Auto Layout anchors
You can make one view fill all available space inside another by pinning all four of its anchors to the same anchors in its parent container. If you use this when the parent container is the view for your view controller, your child view will fill the screen....
How to make gesture recognizers work together using require(toFail:)
It’s common to have multiple gesture recognizers attached to a single view, all doing different things depending on the user’s taps on your screen. By default, iOS lets them fight for control, but usually you want to execute them in some sort of particular order: one gesture should only be matched if another failed. ...
How to make the master pane always visible in a UISplitViewController
Split view controllers on iPad have an automatic display mode, which means in landscape both the left and right view controllers are visible, but in portrait the left view controller slides over and away as needed....
How to make UICollectionView headers stay fixed using sectionHeadersPinToVisibleBounds
Since the earliest days of iOS,
UITableView
has had fixed headers: as you scrolled within a table section the header stayed still, only moving off when another section reached the top....How to make UITableViewCell separators go edge to edge
All table view cells have a separator underneath them by default, and that separator likes to start a little way from the left edge of the screen for stylistic reasons. If this clashes with your own personal aesthetic, you might think it's easy to remove but Apple has made the matter quite confused by changing its mind more than once....
How to make UITableViewCells auto resize to their content
Since iOS 11, table view cells automatically resize to fit their content as long as your cells use Auto Layout to configure themselves. For example, if you use the built-in Basic style for your cell prototype, all you need to do is change the Lines property to 0 for its label and the cell will grow as needed....
How to make UIViewPropertyAnimator scrub with a custom curve: scrubsLinearly
UIViewPropertyAnimator
is an incredibly easy way to build custom animations on iOS, making it trivial to support scrubbable, reversible animations. However, by default scrubbing behaves differently from your regular animation: scrubbing always happens linearly, even if your animation was performed using a curve such as ease-in-ease-out....How to make your user interface in code
Creating your user interface in code gives you the flexibility to build things conditionally, to step through problems in a debugger, to re-use components more easily, and to monitor changes more closely in source control. On the flip side, you lose features like easy segues, static cell design in table views, the ability to preview on multiple devices simultaneously, and more....
How to mask one UIView using another UIView
All views have a
mask
property that allows you to cut out parts depending on what you need. This mask can be any other kind of UIView
, so you could for example use a label to cut out an image view....How to measure touch strength using 3D Touch
You can read a user's 3D Touch strength using the
force
property of a UITouch
, which is best used when compared against the touch.maximumPossibleForce
. For example, you can divide one into the other to see how much relative strength is applied, or do a straight comparison to check to see whether the user is pressing as hard as possible....How to move to the next UITextField when the user presses return
If you’re in a situation where your iOS app has multiple
UITextField
instances lined up, users expect to be able to move between them by pressing Next/Return on their on-screen keyboard. There is no built-in way of making this happen, so we need to write code ourselves using one of several approaches....How to pad a UITextView by setting its text container inset
You can force the text of any
UITextView
to have padding – i.e., to be indented from its edges – by setting its textContainerInset
property to a value of your choosing. For example, to give a text view insets of 50 points from each edge, you would use this code:...How to perform a segue programmatically using performSegue()
Segues are a visual way to connect various components on your storyboard, but sometimes it’s important to be able to trigger them programmatically as well as after a user interaction....
How to position a view using Auto Layout anchors
Auto Layout anchors make it easy to position your views relative to others. There are lots of anchors to choose from: leading and trailing edges, top and bottom edges, center X and center Y, and more. ...
How to print using UIActivityViewController
Printing in iOS used to be done using
UIPrintInteractionController
, and, while that still works, it has a much better replacement in the form of UIActivityViewController
. This new class is responsible for taking a wide variety of actions of which printing is just one, but users can also tweet, post to Facebook, send by email, and any other action that has been registered by another app....How to put a background picture behind UITableViewController
You can put any type of
UIView
behind a table view, and iOS automatically resizes it to fit the table. So, adding a background picture is just a matter of using a UIImageView
like this:...How to read a title from a UIPickerView using titleForRow
As soon as you start using
UIPickerView
for the first time, you realize it doesn't have a built-in way to read the title of any of its items. The reason for this is obvious in retrospect, but don't worry if you didn't get it at first: you should read the title straight from the picker's data source....How to read the battery level of an iPhone or iPad
iOS lets you track the battery level and status of the device you’re running on, which is helpful if you’re overlaying some sort of battery indicator over your user interface. You could even write a trivial app to detect power outages just by plugging in a spare phone then waiting for the charge state to change....
How to read the interface orientation: portrait or landscape?
Apple generally doesn’t want developers to think about things like “portrait” and “landscape” because devices come in a range of sizes, and in the case of iPad you get slide over and split view on top. However, sometimes it’s just useful, particularly on iPhone where the difference between portrait and landscape is huge....
How to recolor UIImages using template images and withRenderingMode()
Template images are the iOS 7.0 way of tinting any kind of image when it's inside a
UIImageView
. This is usually used to mimic the tinting of button images (as seen in toolbars and tab bars) but it works anywhere you want to dynamically recolor an image....How to register a cell for UICollectionView reuse
If you're working entirely in code, you can register a
UICollectionViewCell
subclass for use with your collection view, so that new cells are dequeued and re-use automatically by the system....How to register a cell for UITableViewCell reuse
Reusing table view cells has been one of the most important performance optimizations in iOS ever since iOS 2.0, but it was only with iOS 6.0 that the API got cleaned up a little with the addition of the
register()
method....How to reload a UITableView while preserving selections
When you call
reloadData()
on a UITableView
it will refresh all cells from your data source, but it will also lose any selections the user has made....How to remove a UIView from its superview with removeFromSuperview()
If you created a view dynamically and want it gone, it's a one-liner in Swift thanks to the
removeFromSuperview()
method. When you call this, the view gets removed immediately and possibly also destroyed – it will only be kept around if you have a reference to it elsewhere. Here's how it's done:...How to remove cells from a UITableView
It's easy to delete rows from a table view, but there is one catch: you need to remove it from the data source first. If you don't do this, iOS will realize there's a mis-match between what the data source thinks should be showing and what the table view is actually showing, and you'll get a crash....
How to render an NSAttributedString to a PDF
Attributed strings contain all the formatting they need to go straight to images, PDFs, and other visual output, although it does take a little setup to get a good PDF out....
How to render PDFs using UIGraphicsPDFRenderer
UIKit comes with a built-in class for rendering PDFs, and you can render strings, attributed strings, images, and more right to PDF pages. To get started, just create an instance of
UIGraphicsPDFRenderer
with the paper size you want, then call its pdfData()
method and pass in your drawing instructions. You get back a Data
object, which you can then write to disk however you want....How to render shadows using NSShadow and setShadow()
There are two ways to add shadows when rendering images: calling
setShadow()
and providing offset, blur, and color, or by using an NSShadow
attached to an attributed string. Both have their own advantages, so both are worth trying....How to resize a custom font using UIFontMetrics
Dynamic Type allows developers to adjust the size of in-app text based on user accessibility preferences, but if you use custom fonts it’s easy to forget to add support....
How to respond to the device being shaken
You can make any
UIViewController
subclass respond to the device being shaken by overriding the motionBegan
method. This is use to handle motion (shaking) but in theory also remote control actions – although I can't say I've ever seen someone write code to handle that!...How to run JavaScript on a UIWebView with stringByEvaluatingJavaScript(from:)
If you’re still using the deprecated
UIWebView
, you can run custom JavaScript on it using the method stringByEvaluatingJavaScript(from:)
. The method returns an optional string, which means if the code returns a value you'll get it back otherwise you'll get back nil
....How to scale, stretch, move, and rotate UIViews using CGAffineTransform
Every
UIView
subclass has a transform
property that lets you manipulate its size, position and rotation using something called an affine transform. This property is animatable, which means you can make a view smoothly double in size, or make it spin around, just by changing one value....How to send an email
In the MessageUI framework lies the
MFMailComposeViewController
class, which handles sending emails from your app. You get to set the recipients, message title and message text, but you don't get to send it – that's for the user to tap themselves....How to set a custom title view in a UINavigationBar
Each view controller has a
navigationItem
property that dictates how it customizes the navigation bar if it is viewed inside a navigation controller. This is where you add left and right bar button items, for example, but also where you can set a title view: any UIView
subclass that is used in place of the title text in the navigation bar....How to set prompt text in a navigation bar
You should already know that you can give a title to a navigation controller's bar by setting the
title
property of your view controllers or a view controller's navigationItem
, but did you also know that you can provide prompt text too? When provided, this causes your navigation bar to double in height and show both the title and prompt....How to set the tabs in a UITabBarController
If you're creating your tab bar controller from scratch, or if you just want to change the set up of your tabs at runtime, you can do so just by setting the
viewControllers
property of your tab bar controller. This expects to be given an array of view controllers in the order you want them displayed, and you should already have configured each view controller to have its own UITabBarItem
with a title and icon....How to set the tint color of a UIView
The
tintColor
property of any UIView
subclass lets you change the coloring effect applied to it. The exact effect depends on what control you're changing: for navigation bars and tab bars this means the text and icons on their buttons, for text views it means the selection cursor and highlighted text, for progress bars it's the track color, and so on....How to share content with the Social framework and SLComposeViewController
The
UIActivityViewController
class is the iOS way of sharing almost anything to almost anywhere, but what if you don't want to let users choose? Well, iOS has a tool for that too, although it’s part of the Social framework that get deprecated in iOS 11. That doesn’t mean you can’t use it, but it does mean at some point in the distant future Apple may withdraw it....How to share content with UIActivityViewController
Before iOS 6.0 was released there were a number of third-party libraries that tried to simplify the sharing of content, but even with those libraries in place it was still far too hard. Fortunately, Apple added
UIActivityViewController
, a class that makes sharing to any service as simple as telling it what kind of content you have....How to show and hide a toolbar inside a UINavigationController
All navigation controllers have a toolbar built right in, but it's not showing by default. And even if it were showing, it doesn't have any items by default – that's down to you fill in....
How to stop Auto Layout and autoresizing masks conflicting: translatesAutoresizingMaskIntoConstraints
If you create any views in code – text views, buttons, labels, etc – you need to be careful how you add Auto Layout constraints to them. The reason for this is that iOS creates constraints for you that match the new view's size and position, and if you try to add your own constraints these will conflict and your app will break....
How to stop empty row separators appearing in UITableView
Table views show separators between empty rows by default, which looks quite strange when you have only a handful of visible rows. Fortunately, one simple line of code is all it takes to force iOS not to draw these separators, and it's this:...
How to stop users selecting text in a UIWebView or WKWebView
Using a web view to show rich media easily is a common thing to do, but by default users can select the text and that makes it look a little less like native code. To fix this, add the following CSS to the HTML you load, and users won't be able to select anything again:...
How to stop your UISearchController bar hiding when you scroll
You can embed a search controller right into any view controller that’s inside a
UINavigationController
using code like this:...How to stop your view going under the navigation bar using edgesForExtendedLayout
As of iOS 7.0, all views automatically go behind navigation bars, toolbars and tab bars to provide what Apple calls 'context' – having some idea of what's underneath the UI (albeit blurred out with a frosted glass effect) gives users an idea of what else is just off screen....
How to style the font in a UINavigationBar's title
If you're setting title's in a navigation bar, you can customize the font, size and color of those titles by adjusting the
titleTextAttributes
attribute for your navigation bar....How to subclass UIApplication using UIApplicationMain
Subclassing
UIApplication
allows you to override functionality such as opening URLs or changing your icon, but it’s a non-trivial task in Swift because of the @UIApplicationMain
attribute....How to support pinch to zoom in a UIScrollView
Making a scroll view zoom when you pinch is a multi-step approach, and you need to do all the steps in order for things to work correctly....
How to support right-to-left languages
Hebrew, Arabic, Farsi, and more are all languages that use a right-to-left layout, and it doesn’t take much work to make your iOS apps fit in more naturally for those languages. In fact, there are four things you need to do to get most of the way there, and I want to walk through them briefly with some code....
How to swipe to delete UITableViewCells
It takes just one method to enable swipe to delete in table views:
tableView(_:commit:forRowAt:)
. This method gets called when a user tries to delete one of your table rows using swipe to delete, but its very presence is what enables swipe to delete in the first place – that is, iOS literally checks to see whether the method exists, and, if it does, enables swipe to delete....How to take a photo using the camera and UIImagePickerController
UIKit has a built-in view controller designed to let the user take photos, crop them as needed, them load them directly into your app. Even better, it only takes a few lines of code to use!...
How to use dependency injection with storyboards
Dependency injection is a fancy name for a simple thing: when we create an object in our app, we want to provide it with all the data it needs to work. Before iOS 13 this wasn’t possible when using storyboards, which meant we ended up with properties that were optional or implicitly unwrapped, even though we knew we’d be setting them immediately....
How to use Dynamic Type to resize your app's text
Ever since iOS 7.0 users can set a system-wide preferred font size for all apps, but many programmers ignore this setting much to user's annoyance. You're not one of those developers, are you? Of course not! So here's how to honor a user's font settings using
UIFont
:...How to use IBInspectable to adjust values in Interface Builder
The
@IBInspectable
keyword lets you specify that some parts of a custom UIView
subclass should be configurable inside Interface Builder. Only some kinds of values are supported (booleans, numbers, strings, points, rects, colors and images) but that ought to be enough for most purposes....How to use light text color in the status bar
As of iOS 7.0, all view controllers set their own status bar style by default, which means they can have black text or white text depending on what looks best for your view controller. If you want to have light text in the status bar, add this code to your view controller:...
How to use SFSafariViewController to show web pages in your app
If a user clicks a web link in your app, you used to have two options before iOS 9.0 came along: exit your app and launch the web page in Safari, or bring up a new web view controller that you've designed, along with various user interface controls. Exiting your app is rarely what users want, so unsurprisingly lots of app ended up creating mini-Safari experiences to browse inside their app....
How to use system icons in your app
iOS 13 lets us use icons from a range of over 1500 designed by Apple, all of which come in a variety of weights and sizes. These icons form part of new
UIImage
API, and they are vector-based so you can us them at a range of sizes without loss of quality....How to use UIActivityIndicatorView to show a spinner when work is happening
If you need a simple visual way to show users that some activity is happening,
UIActivityIndicatorView
is the easiest approach. In fact, if you create a dedicated activity indicator view controller, you can cause the whole screen to dim without much code....How to use UIKeyCommand to add keyboard shortcuts
Anyone who connects a keyboard to their iOS device is immediately able to take advantage of keyboard shortcuts – both at the system level and inside apps....
How to use UIPickerView
The spinning, barrel-shaped picker view has been a hallmark component of iOS since the first iPhone, and it doesn’t take much work for you to use in your own apps....
How to use UISearchController to let users enter search words
UISearchController
is a small component designed to make it easy and consistent to add searching to any view controller. Adding it only takes a few small steps: ...How to use UIStepper to let users change number values
UIStepper
is one of those controls that doesn’t get used often, which is a shame – it’s trivial to add, and helps users select a value more accurately than a UISlider
....How to use view controller containment
View controller containment allows you to embed one view controller inside another, which can simplify and organize your code. It takes four steps:...
Showing dictionary definitions using UIReferenceLibraryViewController
UIKit has a built-in dictionary and a built-in way of showing definitions for that dictionary, all done using
UIReferenceLibraryViewController
. Before you try using it, you should call its dictionaryHasDefinition()
method to make sure a definition exists, like this:...What are size classes?
Size Classes are the iOS method of creating adaptable layouts that look great on all sizes and orientations of iPhone and iPad. For example, you might want to say that your UI looks mostly the same in portrait and landscape, but on landscape some extra information is visible. You could do this in code by checking for a change in the size of your view controller and trying to figure out what it means, but that's a huge waste of time – particularly now that iPad has multiple different sizes thanks to multitasking in iOS 9....
What are the different UIStackView distribution types?
One of the most compelling reasons to upgrade to iOS 9.0 is the new
UIStackView
class it introduced, which offers a simplified way of doing layouts in iOS. To give you more control over how it arranges their subviews, stack views offer five different distribution types for you to try, and here's what they do:...What does the message ”Simulator user has requested new graphics quality: 100” mean?
Apple frequently leaves debugging messages in iOS simulator builds, which is both good and bad: it's good because sometimes the information is useful, but it's bad because more often than not it just causes unnecessary worries....
What is a segue?
Segues are visual connectors between view controllers in your storyboards, shown as lines between the two controllers. They allow you to present one view controller from another, optionally using adaptive presentation so iPads behave one way while iPhones behave another....
What is a UIViewController
iOS developers often like to talk about the Model-View-Controller architecture (MVC), where every component in their code is either a Model, a View, or a Controller. This is the standard architecture on iOS, which makes it strange that one of the first types you meet is
UIViewController
– it has both “view” and “controller” in its name, so what is it?...What is a view’s intrinsic content size?
Most views have an intrinsic content size, which refers to the amount of space the view needs for its content to appear in an ideal state. For example, the intrinsic content size of a
UILabel
will be the size of the text it contains using whatever font you have configured it to use....What is an IndexPath?
Index paths describe an item’s position inside a table view or collection view, storing both its section and its position inside that section. For example, the first row in a table would have section 0, row 0, whereas the eighth row in the fourth section would have section 3, row 7....
What is content compression resistance?
When Auto Layout has determined there isn't enough space to accommodate all your views at their natural size, it has to make a decision: one or more of those views needs to be squashed to make space for the others, but which one? That's where content compression resistance comes in: it's a value from 1 to 1000 that determines how happy you are for the view to be squashed if needed....
What is the safe area layout guide?
Before iOS 11 it was common to create views that went edge to edge on the screen, taking up all available space in the glass rectangle of the iOS display. However, from iOS 11 onwards Apple introduced the safe area layout guide, which is a feature that restricts the edges of views so they don’t get clipped by the rounded corners and notch of the iPhone X....
What is the UIAppearance proxy?
If you need to make broad changes to UIKit components, the UIAppearance proxy is your friend: you can treat it like an instance of any given UIKit type, except the changes you make there apply to all new instances of that type. Note: it applies to new instances of that, and won’t change any existing instances you have created....
What’s the difference between frame and bounds?
All
UIView
subclasses have two properties that at first glance seem similar: frame
and bounds
. Both return a CGRect
– a rectangle containing their X and Y position, plus their width and height – but that doesn’t mean they are the same....What’s the difference between leading, trailing, left, and right anchors?
If you wanted to pin a button to the left edge of its parent, you might write code like this:...
Why can I not register for push notifications?
When you register for push notifications, one of two methods ought to be called:
didRegisterForRemoteNotificationsWithDeviceToken
is called when everything worked correctly, and didFailToRegisterForRemoteNotificationsWithError
is called if something went wrong....