NEW: Pre-order my Vapor book and learn server-side Swift! >>

UIKit

Found 100 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 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 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 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 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 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 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 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: bringSubview(toFront:). Here's an example:... 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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:)

You can run custom JavaScript on a UIWebView 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 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 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 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 use Dynamic Type to resize your app's text

As of 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 >>

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 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 >>

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.

Get six books for only $150

The Swift Power Pack includes my first six books for one low price, helping you jumpstart a new career in iOS development – check it out!

Click here to visit the Hacking with Swift store >>