FREE: Read a new Swift article every day – click here! >>

UIKit

Found 166 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.... Continue Reading >>

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:... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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 problems.... Continue Reading >>

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.... Continue Reading >>

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 as of iOS 5.0 you can add more than one to either side.... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.”... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

How to change your app icon dynamically with setAlternateIconName()

iOS 10.3 finally gave 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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

How to fix incorrect VoiceOver pronunciations

As clever as VoiceOver is, sometimes it will get the pronunciation wrong for certain words – particularly when it’s missing some context that would have made clear what the correct pronunciation was.... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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?... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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).... Continue Reading >>

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:... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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!... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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:... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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!... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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:... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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?... Continue Reading >>

What is a view’s intrinsic content size?

All 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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

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.... Continue Reading >>

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions, all written for Swift 4.2.

Upgrade your apps!

Take on Core ML, ARKit, PDFKit, Core NFC, and more all in one book that's packed with practical projects!

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>