100 Days of Swift | Swift tutorial for beginners |

Design and Code an iOS 11 app from scratch

We’ve come a long way since the release of Swift. In a surprising turn of events, code has become a common skill for designers, thanks to designer-friendly tools like FramerStoryboard, and emerging languages like React. Interesting, many believed that it would be the other way around, that code would slowly disappear. What they tend to forget is that people will always choose power if the convenience gain is marginal. Code has become much simpler and more standardized over the years. It’s also an order of magnitude more powerful than it was, in a way that design tools can’t quite catch up to.

For example, today you can do ARKit, a way to bring virtual 3D assets into reality through the lens of the phone. This can’t be achieved yet in a drag and drop user interface.

Animation is another hot topic for designers. What many don’t realize is that the cost of executing intricate animations in code is almost the same as learning another animation tool. Design tools like Origami are increasingly complex while code continues to be simplified. At the same time, you learn a valuable skill that has no ceiling set by a graphic user interface. That coding experience can easily transfer between Swift, Framer and React.

A designer that can code is more valuable than one that doesn’t, given that both designers are equally skilled in design.


To follow this course, you can download the source file, which will help you compare your progress.

State of Swift

We’re currently in the 4th release, which means that your code will less likely break when an upgrade is around the corner. Swift is now simpler and more stable. In 2017, it became one of the top 10 languages, even as a relatively new language.

Xcode 9

Xcode 9 introduces Dynamic TypeSafe Area guides and a better experience previewing on multiple devices. The code editor now supports Markdown, a simpler format for writing. Code styling and highlighting is more powerful, and scrolling is butter smooth, even for large files. Refactoring is another fantastic addition, making it effortless to rename your classes and objects.

The new GitHub integration is much deeper, allowing you to commit and pull changes without leaving Xcode. Finally, you can now test on your app on multiple iOS Simulators at once, or on your own device wirelessly, which wasn’t possible before.


Empowering Designers

Personally, I spent close to 20 years making Websites. Beyond Photoshop and Sketch, I learned CSS, HTML and Javascript. I wouldn’t trade anything for those skills. It allowed me to be where I am today. I can design and build fairly ambitious Web and iOS apps in a way that isn’t restrictive or unrealistic.

Knowing how to implement your own designs is both empowering and informative. It’s like getting feedback in real-time, as you design. That feedback is fed by your understanding of engineering, preventing you from making common design mistakes, which can cost weeks of lost time.

No designer wants to spend a week putting together something only to be told that it can’t be done.

You Don’t Have to be an Expert

Knowing how to use Storyboard, Auto Layout and a little bit of Swift will not only allow you to build your own app, but also share the workload with your developer. You don’t work in a silo, you iterate at the same pace as your team. A project can only move as fast as its slowest link. Development takes 80% of the time; the first 20% is attributed to visual design. There is 30% up for grab. Since designers are especially trained for that part, there can be a huge win.


Building Your First App

In this large chapter, we won’t skip any steps. You’ll learn everything in great detail: the Xcode user interface, Storyboard, Auto Layout, Animation, the Swift language and a whole lot more. Each section is extremely visual and has videos with voice as well as downloadable Xcode projects. The whole process has been simplified for both designers and beginners.

Quick Prototyping

While Xcode allows you to do really powerful interactions, it can also create simple prototypes. And without writing a single line of code. Unlike a lot of prototyping tools out there, Xcode uses Storyboard, which is a lot more visual and a lot closer to the way designers work in Sketch.


Designing in Storyboard

The Storyboard works very similarly to Artboards in Sketch. It’s incredibly intuitive once you get past that fear of Xcode. In Storyboard, you manipulate your UI in a very visual way. It’s even easier than HTML and CSS because you don’t need to code.

As a designer, to be able to implement your own design is empowering, not to mention fun as well. We’re fortunate to have a functional visual tool like Storyboard that even developers use. Not only can you prototype with it, but also you can create production-quality layouts that co-exist with production code.


Auto Layout and Stack Views

Adaptive Layouts is one of the most important skills you can develop. As there is a growing number of mobile devices and screen sizes, we can no longer afford to focus on just static designs.


Adapting for iPhone X

The iPhone X introduces the need to follow the Safe Area layout guides. The Safe Area ensures that your content won’t be hidden by the Notch or corner radius. In general, background elements such as background images and colors should follow the Superview while the content such as labels, avatars and medias should follow the Safe Area.


Learning Swift as a Designer

With Swift Playground, you can experiment with code in real-time. It’s a perfect place to experiment with all the possibilities without the limitations of a GUI. Learning how to use functions, classes and working with UIKit can make your app infinitely more powerful.

I like to think of code as another design tool. Software is made of code, it is unavoidable.

This book was written in a way that it respects all the latest standards encouraged by Apple. I consulted seasoned iOS engineers in the process and they kindly reviewed all the code to make sure that I respect the best practices.


Why Learn Code?

As a designer learning code, you can perform any animation, complex interactions and work with real data from any database or API. Also, you can collaborate better with engineers by understanding their constraints, and pushing beyond those constraints.

Animate in Playground

Playground allows you to quickly test snippets of code and see the results in real time. There are a few techniques that you need to know in order to start on the right foot. The beautiful thing about Playground is that there is zero setup, and you just need to write a bunch of words that make sense to the computer. But you need to enable a couple of options.

We’re going to learn how to build a simple transition from the Main screen to the Section screen. While Playground may not allow you to test on devices, the code that you create here can easily be transported to Xcode. We’re using Playground to get a firm grasp at some of the basic concepts of animating in Swift.


3D Animation

A lot of interesting interactions happen as a result of scroll events. In the Design+Code app, we use the scroll information to capture the read progress, to show or hide the navigation bar, and to apply a parallax effect on the visual elements.

CATransform3D is a fantastic way to take your animation to the next level. There is so much more to explore in term of using the matrix values and playing with rotatescale and translate. Our final result is something that will leave quite an impression on our users.


The Final App

In this course, you’re not doing a sample app. You’re building a real app that’s been published to the App Store. You’re facing real world problems and you’ll learn advanced techniques like using Libraries, gesture interactions, implementing Dark Mode, JSON parsing, Realm database and publishing to the App Store.

Introduction to Xcode 9

Every year, Apple introduces a new version of Xcode, greatly improving the tools and making available a number of new APIs in order to make iOS development easier and more powerful. There is a lot to explore in Xcode. Before going too deep, I’d like to start with the basics. Let’s go ahead and make our first app!


To follow this course, you can download the source file, which will help you compare your progress.

To follow this tutorial, you’ll need Xcode 9

Xcode’s Welcome Screen

First, let’s download Xcode in the App Store. The first time you run Xcode, you’ll see this screen. This is the starting window, allowing you to start a Playground file, create a new Xcode project or Clone an existing project.

A Playground allows you to experiment your code and see results in real-time. Before writing a lot of code, I think it’s important to have fun with the user interface first. As for Cloning, this is something we’ll explore later.



Let’s click Create a new Xcode project. In this screen, you’ll find a bunch of starting templates for different needs, ranging from iOS, macOS to tvOS. Normally for an iOS app, you’ll want to use Single-View Application. Go to iOS > Application > Single View Application.



This is where you’ll set your project and organization names. Set the name of the app DesignCodeApp.

The Organization Name is your name, or your company name. The Organization Identifier is typically your domain name in reverse. Language will be Swift. Let’s check CoreData since we’ll need it later.



Click Next. Now, save the Project to your Mac, typically in Downloads or Documents. Make sure to enable Create git repository on my Mac; this allows you to keep a version history of your project. It’s similar to Abstract.

Finally, click Create. That’s it, you’ve created your first iOS app!


Xcode’s Layout

The first time you land in Xcode, it’ll look overwhelming. Rest easy, I’m here to guide you. I like to compare Xcode to a big, do-it-all application like Photoshop, because as a tool, you can really do anything with it. You can build your dream app without jumping between many applications. It’s scary at first, but once you learn how to navigate through the complex layout, you’ll love features such as Assets Catalog, Storyboard and the iOS Simulator.

But unlike Photoshop, Xcode is unavoidable. The large majority of iOS developers use it. You need everything in Xcode for designing, coding, testing, debugging and a multitude of other tasks. After 3 years of developing for iOS, I still find myself learning simpler ways to design things and that’s really exciting. So that’s why I’m writing this book. I want to teach you my workflow and guide you through this experience. Now, let’s explore some of the most important aspects of Xcode.


The Toolbar

First, the toolbar. Just like most Mac apps, the toolbar is always present. It allows you to quickly do things that you often perform.

The left part of the toolbar lets you runstop and select which device to test on. If you have a registered device, you can even test on your iPhone. Since we’re working with an iPhone 8 design, let’s select the iPhone 8.

The middle portion shows you what’s going on with your app. Whenever you have warnings or errors, it’ll show up there.

The right part shows the editor and utilities. The show/hide tools on the far right are especially useful for showing and hiding parts of your Xcode UI. Because Xcode can be pretty busy, I suggest hiding parts that you don’t need. Useful keyboard shortcuts are: Command + 0 to show/hide the Navigator and Command + Option + 0 to show/hide the Inspector.


Project Settings

Your project is already set up and ready to go thanks to the first dialog you filled. But if you need to edit settings, this is where you go. For example, you can select which device orientations to support. Also, you can change your status bar style to Light or Dark, or completely hide it.


The Project Navigator

If you’ve ever built a Website, you’ll remember that a site always starts with a few files: index.html, images, css and javascript files. Well, the same concept applies here. The project navigator is a reflection of your own Xcode project folder.

.swift files are the equivalent of your javascript files. They allow you to script your app. AppDelegate.swift is where you put all the scripting at launch. ViewController.swift is your screen. Normally, you create a new script per screen. Main.storyboard is where you do all the layout and styling. Assets.xassets is where you put all your images. LaunchScreen.storyboard is where you set up the first launch screen.

The M means that the file has been modified. That’s because we enabled up Create git repository on my Mac. It’s like in Abstract for Sketch. If you’re not familiar with Git, I suggest watching this video.


The Other Navigators

Above the main Project Navigator, you’ll notice a bunch of sub-navigators. They’re mostly for source control, searching and debugging, which you can ignore at this stage. However, whenever your app crashes, Xcode will automatically change to the Debug Navigator tab. As a beginner, you probably won’t understand much, so I suggest to always go back to the first Project Navigator to avoid being lost.



Just like most Mac apps, Inspectors on the right are used for editing selected elements. This is purely contextual, so we’ll explore more when we edit specific elements.

The Asset Catalog

One of my favorite features about Xcode is how easy it is to organize images for different resolutions. In the Asset Catalog, you can quickly edit your AppIcon and images for your app.


Using Apple’s Icon template, you can quickly export icons of all sizes and resolutions for both iPhone and iPad. You can drag and drop the images to their respective fields, by following the size in pt, at 1x, 2x or 3x.



For the rest of the assets, we’ll mostly use PDF files, since it can be challenging to manage 3 resolutions per asset. Except for backgrounds, photos and avatars, PDF is the perfect choice for glyphs and other flat vector assets. But, just like SVG, PDF can act weirdly sometimes, depending on how you set up your glyphs. So, it’s nice to have the PNG format as a backup.

Instead of generating 3 images (1x, 2x, 3x) per asset, you only need one single file. In Sketch, you need to export them in PDF at 1x. However, there are a few things to note. The resolution matters. You must export at 1x to make sure that it looks good in Storyboard. Xcode re-renders them to PNG files to 1x, 2x and 3x for you.

To import your assets, simply drop the entire folder. If named correctly, Xcode will automatically bundle the assets together in their respective resolution.


Themes for Xcode

Xcode is filled with options. It’s best not to cover all of them right now, since it would only distract you from building the actual product. But there’s a pretty neat feature that allows you to change the code theme in Xcode. Go to Xcode > Preferences > Fonts & Colors. There you can choose the Dusk theme, which is my favorite.


Running your first App!

Now that you’re getting familiar with the way the layout works, let’s run your first app by clicking on the Run button. If you didn’t do anything terrible, like deleting files by accident, an iOS Simulator will come up. This how your app will look like as you build it. It’s fully interactive.

The first time that you’re running your app, it’ll just be a blank white screen.

While it may be tempting to run your app on iPhone X, one thing to note is that the performance isn’t great. That’s because the iPhone X renders at 3x, so on the iOS Simulator, the experience isn’t great. On the other hand, running on the device is butter smooth!


Customizing the iOS Simulator

You can change the size of your iOS Simulator by going to Window > Scale > 100%, or by pressing Command + 1, 2 or 3.

You can press Command + Shift + H to go back to the Home screen and play with iOS’s default apps like Safari or Settings. Safari is extremely useful for testing your site, especially on the iPhone X device.

New in Xcode 9, you can open multiple Simulators at once!

To rotate, use Command + Right Arrow or Left Arrow. To reset the content, just go to File menu > iOS Simulator > Reset Content and Settings. Finally, you can take screenshots by pressing on Command + S.

Xcode Source Control

Let’s go back to Xcode and save our current changes into a version, so that we can keep a history. This also allows us to go back to previous versions when mistakes happen, or collaborate with teammates. To do that, go to Source Control and click Commit…. Then, enter a description of your commit like “Added the assets” and click Commit Files. Once that is done, you’ll notice that the M next to Assets.xcassets will disappear. This simply means that the changes were saved in a version.

Every time you finish a feature, task or section, it is recommended to commit your changes.



This concludes the short intro to Xcode. These are the features that I use the most for building apps. As for the rest, you’ll learn them progressively as we face problems.

Introduction to Storyboard

Storyboard works similarly to Artboards in Sketch. It’s incredibly intuitive once you get past that fear of Xcode. In Storyboard, you manipulate your user interface in a very visual way. It’s easier than HTML and CSS because you don’t need to code.


To follow this course, you can download the source file, which will help you compare your progress.

Storyboard Layout

To reach Storyboard, click on Main.storyboard in your left Navigator. First, let’s hide the left Navigator by click on the left icon in the far right of the Toolbar. Then, let’s show the Document Outline by clicking on the little icon at bottom left of the Storyboard UI.

Once you do these steps, your Xcode app should look like the image below. iOS development has a different naming structure. When talking to a seasoned developer, it’s important to be on the same page as them. They may not understand what an Artboard is, but they’ll get what a View Controller is.


Document Outline

Just like in Sketch, this is where you’ll find all your layers. In Xcode, we call them objects. When you’ll drag and drop elements, you’ll be able to navigate them here. To enable this, click on the small icon at the bottom.


View Controller

The middle part is your Storyboard editor. You’ll find all the screens for your app. They’re like your Artboards in Sketch. We call them View Controllers. But, unlike Artboards, we’re building a truly interactive experience, with animations, data and constraints.

You can quickly preview different iOS devices in Portrait or Landscape by clicking View as: iPhone 8. This will bring up 8 different devices to preview on. This option is especially useful for checking if your app is adapting well across devices.



Sometimes, you’ll find yourself with a lot of screens. You’ll need a way to zoom out. You can do so by pinching your trackpad or simply double clicking outside the View Controller.


On the right, you’ll find the Inspectors. Just like in Sketch, this is where you’ll edit the colors, font size, images of your objects. 90% of the time, you’ll use the Attribute and Size Inspectors. It’s important to be familiar with them since most of the user interface changes will happen in these two inspectors. They are very specific to the object that you select.

For example, select the View in the Document Outline, and you’ll find these Attribute options. You can change the background color, the Alpha opacity and a bunch more options.

In the Size Inspector, you can change the xy position as well as the width and height. Since the View is just a background, those properties can’t be changed. Once we bring in new elements like buttons and texts, we’ll be able to.



The File, Identity and Connections inspectors are more global.

The File Inspector is Storyboard-specific. You can disable Auto Layout or Size Classes for the entire Storyboard.

The Identity Inspector lets you connect your View Controller to a Class. Classes are your Swift files – they let you script animations and data to attach to your objects. A View Controller in Storyboard can be connected to a ViewController.swift Class file, similar to how you include a javascript file to an HTML file.

The Connections Inspector manages the connections between your View Controller’s Objects to your Swift file’s code. We’ll see this more in action later.


Object Library

On the bottom right, you’ll find the Object Library. That’s the 3rd tab. The Object Library has all the UI components that you can use for your layout. It’s like Insert in Sketch.

This is where you drag and drop the objects you need for your app: buttonsimagestexts, etc. I suggest playing with them as much as you can and see what works. It’s really fun to discover new ways to use them! As designers, we love to customize things and break that “default” look. Learning these objects will empower you to customize as much as you’d like without being completely unrealistic.

To change between List View and Grid View, you can click on the small icon in the bottom left.


The Media library

Right next to the Object Library, you’ll find the Media Library. Once you have imported all your assets, you’ll be able to access them from the Media Library. This is really useful because every time you add assets to your Asset Catalog, they’ll appear here, allowing you to drag and drop to your View Controller.



So far, we’ve become familiar with the Xcode user interface and learned how Storyboard is composed. We’ll need this to be able to start implementing screens in Xcode.

Quick Prototyping in Xcode

While Xcode allows you to do really powerful interactions, it can also create simple prototypes. And without writing a single line of code. Unlike a lot of prototyping tools out there, Xcode uses Storyboard, which is a lot more visual and a lot closer to the way designers work in Sketch.

Just by learning how to replace images in the Asset Catalog can be a huge help to your team. No longer should designers be constantly nagging developers to do simple pixel perfect fixes. Instead, they can just do these tasks themselves.

As a result, you’ll learn pretty neat tricks. For example, did you know that you can animate elements strictly in Storyboard. For each object, you have a hefty amount of options, giving all the tools to set interactions, animations and ultimately, make your layout adaptive.


To follow this course, you can download the source file, which will help you compare your progress.

Import the Screens

It is important to hide the status bar in your screens, since the device has its own bar that shows the time and status icons. In Asset Catalog, drag and drop the Screens folder.


Creating New View Controllers

Go back to Storyboard. In your Object Library, let’s drag in new View controllers for our screens: HomeChaptersBookmarksExercisesMore and Article. You can definitely import as many screens as you want, but to simplify this tutorial, we’ll just focus on these 6 screens. You can zoom out by double-clicking outside the View Controller to make things easier. Your Storyboard should look like this.


New Screens from Media Library

Now let’s go to Media Library and find those screens. Scrolling through all the assets may be a little overwhelming, so let’s use the filter at the bottom and type “screen”. If for some reason, you still can’t find them, you may need to restart Xcode for them to appear. Finally, drag and drop each screen to a view controller, starting with Home.


Initial View Controller

You might have noticed the arrow next to the first View Controller. That arrow means that it’s the first screen that’s going to be loaded when the app is launched. You can move the arrow to whichever screen by dragging it around.


View Controller is Unreachable

If you Run the app, it’ll get stuck on the first screen. You can’t go anywhere from there.

In addition, you can see a warning in the Storyboard’s top navigator. Click on it, and you’ll see a message saying “View Controller is unreachable”. That simply means that you have screens that are not reachable.

As a side note, I suggest paying attention to these messages as they’ll make suggestions on the best practices for your app. I always try to keep them at zero. Most importantly, if they’re red, you have to fix them right away, or you won’t be able to run your app at all.


Creating a Button

To connect one screen to another, you’ll need a Segue. To create one, you’ll need a Button in your View Controller. Let’s drag a Button to the first screen. Like in Sketch, just drag the object around and double-click on it to remove the text. It’s a transparent button.


Creating a Segue

This is a very important technique for connecting objects together. It’s not obvious at first, but essential to Storyboard. To create a segue, you’ll need to Control + Drag the button, to the second screen. A blue line will appear. Drop it on the second screen.

When you create a segue, you get 3 options: PushModal and Custom. Push requires a Navigation Controller, so we can’t use this for now. Modal is the most versatile one since it just loads the second screen on top of the first one. Custom is more advanced, so we don’t need it for now.


Editing the Segue

Once created, you can click on the arrow between the 2 screens. When you do, you’ll find a bunch of options in the Attribute Inspector. Let’s select Transition and choose Cross Dissolve. It’s a simple Fade In animation.



There are 6 types of default transitions between screens in iOS: Cover Vertical,** Flip Horizontal, **Cross DissolvePartial CurlNone **and **Push (requires Navigation Controller).


Previous Screen

Once we reach to the second screen, we’ll need a way to go back to the previous screen. In this case, we’ll just create a Button that takes up the entire View Controller. Then, create a segue back, with the same Cross Dissolve transition.


Duplicating Buttons

Now we just need to repeat the same steps for every screen. From the first screen, we’ll have 4 buttons for each Tab Bar icons. Like in Sketch, you can Option + Drag from the first Button to create duplicates. Then, for each Button, create a segue to ChaptersBookmarksExercises and More respectively.


Copy and Paste Buttons

For each of those 4 screens, create a Button back to the Home screen. You can Copy and Paste a Button from one screen to another. However, you’ll need to adjust the Button a little by dragging and using the Smart Guides. Finally, create a segue back to the Home screen.


Selecting from Document Outline

Once the segues are created, select all of them from the Document Outline and set the Transition to Cross Dissolve.


Scrollable Content

You may have noticed that we didn’t do anything for Article screen. That’s because the content there is taller than the actual View Controller. For this, we’ll want to use a Table View Controller instead. It has an embedded Scroll View, which lets you scroll the content. Drag and drop a Table View Controller from the Object Library. Then, Command + C the image from Article and paste to that Table View Controller. Finally, you can delete the Article View Controller.


Button To Article

Now, let’s create a connection to the Article screen. From Chapters, create a Button that covers one of the cards. The size is x15y255width310 and height245. Then, create a segue to Article. Again, select the segue and apply the Cross Dissolve Transition.


Tap Gesture Recognizer

Since we can’t put a Button on top of the Article image in the Table View Controller, due to some technicalities that will be explained later, we’ll use a simple Tap Gesture Recognizer. A gesture can be attached to any element to recreate that same tap interaction that a Button has. Drag a Tap Gesture Recognizer from the Object Library and drop it on top of the Article image. Once completed, you’ll find it in your Document Outline. From there, do the same Control + Drag to the Chapters Screen and set the segue to Cross Dissolve.


Remove Prototype Cell and Content Insets

You’ll notice that the Table View Controller has Prototype Cells above the image. To remove that, simply click on Table View in the Document Outline and set Prototype Cells to 0. Last but not least, you’ll find an empty space left. To disable to that, go to Size Inspector, and set the Content Insets to Never.



With this, your prototype is done. Let’s run it and give it a test. With these techniques, you can really build a simple flow using real development techniques. That knowledge, although basic for now, can really expand into something interesting in the future. It’s like learning CSS all over again. Let’s take a look at our prototype.

Swift 4 Playground

Since its release, I’ve come to really enjoy coding in Swift. I have a Web background and over the past 20 years, I’ve witnessed first-hand how programming languages have become simpler, more powerful and more modern.

Swift is Apple’s way to modernize their decades-old language Objective-C. It’s not only shorter, more familiar but also safer. All my new iOS app are completely written in Swift. I’ve made the switch entirely. I’d go as far as saying that I’ve never enjoyed a language more than Swift.


To follow this course, you can download the source file, which will help you compare your progress.

Instant Feedback

Unlike many programming languages on the Web, Swift is safe. In other words, you’re told in real-time when you make mistakes. This prevents you from having to trace back hundreds of steps to see what you did wrong. This is a feature that will blow your mind once you understand it, but will irritate you when you don’t, because you won’t be able to run your app until you fix your code. Imagine that you’re drawing a rectangle and Sketch tells you that it’s not well-centered. In code, that’s actually a tremendous help.

I wrote Card with a capital C and instantly, I was given an error. The code becomes white and autocompletion stops working.


Xcode Code Completion

Swift Playground is a big help for experimenting with code and checking the results in real-time. The autocompletion is one of my favorite features in Xcode. As a beginner, I don’t encourage you to complete your code, because the autocompletion kicks in and you just need to select one of the options. It’s safer this way. Swift is case sensitive, so there is a difference between uibutton and UIButton. Autocompletion knows automatically if that code can be used or not. If true, you have access to more contextual suggestions.


Create your First Playground

First, let’s create a new document in Swift Playground. On Xcode’s welcome screen, click on Get started with a playground. Select Blank. Then, save DesignCode-Swift to a folder like Documents.


Constants and Variables

Like most programming languages, you can declare variables and objects so that you can use it, or change it later. Think of variables as Sketch Symbols, where you can re-use them or modify its content. When you declare something, you can use let or var. The biggest difference is that a let will never change its value, but a var can.

I know that my name will never change.

let myName = "Meng"

But my age will change every year.

var myAge = 35
myAge = 36

It is recommended to use let as often as you can to make your code clear, but hey, if you’re starting, don’t worry too much. Use var if you’re not sure. That’ll prevent you from getting errors that you may not understand. As you get more comfortable, you’ll learn to use let more. Regardless, Xcode will make the correct recommendations if a var isn’t properly used.

Some basic errors are pretty hard to understand for beginners. If you do get into this situation, just Google it and look for StackOverflow answers. This error means that you can’t change a let value. So you’d have to use var. One of the great things about code is that it’s fairly easy to Google for solutions, unlike visual design problems.

Value Types

Unlike Objective-C, you don’t have to write the type explicitly anymore. Swift will assign the type automatically, making the code shorter.

let myJob = "Designer"  // String
let myYear = 1982       // Int
let isLearning = true   // Bool

Of course, you can still be explicit.

let myTwitter: String = "@MengTo"

But different types can’t be mixed.

let label = "the width is "
let width = 100
let widthLabel = label + String(width)

I had to convert the width (Int) to a String in order to be able to combine it with label (String).

Tip: you can hold the Option key and click on a value to see its type.



Wouldn’t it be cool if we can store some colors in our palette so that we don’t need to hard code it every time?

var colors = ["red", "green", "blue"]

Now, let’s get our color. Notice that the index always start with 0.

colors[0] // red

What if we want to add a color to our list?


Let’s remove the green color.

colors.remove(at: 1)

Control Flow

Often times, we want to set conditions before running something, or we want to loop and duplicate stuff.

Here’s a condition.

if myAge > 30 {
    print("I'm old")
} else {
    print("I'm not old")

We’re using print to print a message in our console, which is useful for checking if our code works. Console messages don’t appear to your users.

But that’s 5 lines of code. To make it shorter, you can do this instead.

myAge > 30 ? print("I'm old") : print("I'm not old")

However, when you have too many if statements, it can become unreadable. So use switch for multiple conditions.

switch myAge {
    case 30...100: "I'm old"
    case 18...29:  "I'm an adult"
    case 0...17:   "I'm young"
    default:       "Not sure"

For Loops can be used to iterate over items in an array.

for color in colors {
    print("This color is \(color)") // prints 3 times

Notice that in our print, we can inject a variable by using () inside a String.


function is a re-usable task. Think of it like a Sketch Symbol, allowing you to re-use the same element or group of elements across the project.

Let’s make a function that converts points to Retina pixels. We know that 1pt equals 2px in Retina. After we export assets at 2x, the size of the asset doubles.

This is how you write a function.

func pointToRetina() {

We’ll need to feed it with a point value. Notice that we have to be specific with the type Int, since we’re working with numbers. Then, we’re multiplying the point by 2.

func pointToRetina(point: Int) {
  point * 2

But of course, you want to return the Retina value, so you add this arrow sign ->. But when you do that, your function needs a return line, otherwise Swift is going to give you an error.

func pointToRetina(point: Int) -> Int {
  return point * 2

Let’s call the function somewhere in our app.

pointToRetina(point: 320) // Returns 640

Class and Struct

All the above code is extremely useful for writing clean, re-usable code. But sometimes you’ll want to create a profile instead of just performing tasks.

struct UserStruct {
  var name: String
  var age: Int
  var job: String

Now you can create a new user.

var user = UserStruct(name: "Meng", age: 35, job: "Designer")
user.name // Meng

Classes and Stuctures are almost the same thing, except that the struct automatically provides an default initializer for all properties, the class doesn’t. You don’t need to assign a value to all properties. For the Class, you have to write an initializer.

class UserClass {
    var name: String
    var age: Int
    var job: String

    init(name: String, age: Int, job: String) {
        self.name = name
        self.age = age
        self.job = job

struct is a value type. It gets copied if you pass it around. Now we have two separate objects. userB is a duplicate of userA. If you change a property of userBuserA won’t change.

var userA = UserStruct(name: "Meng", age: 32, job: "Designer")
var userB = userA
userB.name = "Marcos"
userA.name // Meng

class is a reference type. That means it gets referenced if you pass it around. If we change the name of userBuserA also change.

var userA = UserClass(name: "Meng", age: 32, job: "Designer")
var userB = userA
userB.name = "Marcos"
userA.name // Marcos


Comments are not always necessary as long as your code is readable and concise, and that there is no magic going on. A lot of iOS developers that I’ve worked with don’t like comments because it adds distractions to the code. But for complex logics, it’s okay to comment.

// My comment
/* This is a comment
 written over multiple lines */


New in Xcode 9, you can use Markdown to inject rich content in your Swift files like titles, links and images. In order to view the rendered Markup, you need to enable it in Editor > Show Rendered Markup.

Headings are important for setting a structure to your texts. The more #, the smaller the title gets.

//: # Heading
//: ## Second Level Heading
//: ### Third Level Heading

Typically, you’d use this for single-paragraph comments.

//: Markdown text

 Markdown text over multiple lines. To use bold, do **bold**, like this. For italic, use *italic*.

One of the biggest advantages of using Markdown is the ability to cleanly transform words into clickable links.

//: Learn Swift 4: [Design+Code](http://designcode.io)

When you’re creating a tutorial in Swift, having images can help a lot to help visualize the code. To insert an image in your Playground, make sure to enable the Navigator by pressing Command + 1. Then, drag and drop an image to Resources.

//: Logo: ![Image](Logo.jpg)



Code Sections

Xcode has a pretty useful way to browse code. You can click on the navigation bar of your code editor and search by typing the word. It is recommended to put similar functions together in your Class file and give them a section title.

Marking your section

// MARK: Section


Naming Convention

In this book, we’re going to follow the Apple standards of naming things.

For variables and functions, we’re going to use camel case starting with a lowercase.


For Classes and Structs we’ll capitalize the first letter. Notice that ViewController.swift is a Class.


Avoid using abbreviations. Your code has to be readable by anyone. It has to read like English.

var u = UserProfile()

What the hell is “u”? Just like in design, don’t make your code ambiguous. Make it clear, clean and functional.


One of the hardest things to work with is data. That’s because data often returns no value.

Swift introduced Optionals to make your code safer. You apply a question mark (?) to variable that may return no value.

var answer: String?
UILabel().text = answer

This means that you’re expecting that answer sometimes has no value.

When you’re sure that there is a value, you can add an exclamation mark (!).

var answerString: String!

Optional Binding

Sometimes, to avoid breaking code, you may not want to run your code unless there is a value. So you use Optional Binding.

if let sureAnswer = answer {
    UILabel().text = sureAnswer

You can make that code shorter by doing this.

UILabel().text = answer ?? ""

If answer has a value, use it, otherwise return an empty string.


That’s it, we’ve learned some Swift basics. We’re going to use all of this for the making of our app. It’s okay if you didn’t understand everything, at least you have some idea of what they when you encounter them. You’re definitely going to get better with practice.

Design in Playground

Playground allows you to quickly test snippets of code and see the results in real time. There are a few techniques that you need to know in order to start on the right foot. The beautiful thing about Playground is that there is zero setup, and you just need to write a bunch of words that make sense to the computer. But you need to enable a couple of options. We’re going to recreate some basic UI elements.

Normally, we’re not gonna need to design the user interface in code. We would use objects in Storyboard for that. But for things that needs to be dynamic and interactive like Labels, Buttons and Colors, we’ll want to edit them in code. In turn, that will allow us to animate those elements and feed in real data later.


To follow this course, you can download the source file, which will help you compare your progress.

Create a Playground

Let’s create a new document in Swift Playground. Let’s go to Xcode’s welcome screen and click on Get started with a playground. We’ll select Single View. Then, save DesignCode-Design to a folder like Documents. At this time, we’re not too interested in application logics. We want to code UIs.


Single View Playground

Single View gives us a starting template that includes a white View Controller, with a Label of 200 x 20 pt.


Enable the Preview

To see the live preview of your code, you can enable Show the Assistant editor in the far right of the toolbar. Once enabled, it’ll show you what the View Controller looks like.



In the first line, you’ll find import UIKit. This simply means that we’re using the iOS framework called UIKit by Apple, which pretty much powers everything you see in iOS. Apple has made it really easy to design and build powerful apps without the need of a single library. Anything from ARKit, to multiple ways to animate, in-app purchases are provided in UIKit.

Playground Support

In the second line, we’re using import PlaygroundSupport, which allows us to preview animations thanks to the following code at the end:

PlaygroundPage.current.liveView = MyViewController()

This last line simply means that we’re using PlaygroundPage from the library PlaygroundSupport to create a live preview of the View Controller.

View Controller

We’re starting a View Controller class called MyViewController. A View Controller is the equivalent of an Artboard in Sketch. This screen is already set up with a white background and a black text that says “Hello World”.

class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let label = UILabel()
        label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
        label.text = "Hello World!"
        label.textColor = .black

        self.view = view


Let’s customize the label to recreate the title in the final screen. Change the frame’s position and size to the following. Pretty straightforward, since these values are common in most design tools.

label.frame = CGRect(x: 16, y: 16, width: 272, height: 38)

Let’s change the label.text to ”Learn Swift 4”. Already, you can see how changing the code affects the screen content.

label.text = "Learn Swift 4"


For the card, we’ll use a UIView. The UIView can be compared to a Rectangle in your design tool. You can set a bunch of properties like background colors, rounded corners and drop shadows. We’ll name it cardView. The first word card is for describing what the object is. View is important for calling the type of element.

let cardView = UIView()

As soon as you type UIView, you’ll notice an autocompletion window that shows you the suggestions based on what you’re typing. We can just press Enter to complete UIView. Then, type the left parenthesisright parenthesis. This simply means that we’re initializing the object UIView.



With cardView declared, we’re going set the frame property. When you type frame, you’ll see what kind of value it is. In this case, it expects a CGRect. A CGRect is basically a rectangle. Type equalCGRect, then press Enter to autocomplete. Type ( in front to show another suggestion window and select the 5th one. Start filling the x, y, width and height values. You can use Tab to move to the next value.

cardView.frame = CGRect(x: 20, y: 255, width: 300, height: 250)



Let’s set a background color for cardView using the property backgroundColor. What you’ll notice here is that backgroundColor is expecting a UIColor as a value. You can type UIColor, dot, blue. Blue is a preset color among a few others like white, black, red, etc.

cardView.backgroundColor = UIColor.blue

Adding a Subview

Once we have a cardView with a frame and a color, it should be visible. Let’s go ahead and add it to the screen. In order to do that, we’ll use the addSubview method.



Avoiding Repetition

Since Swift already knows that backgroundColor is a UIColor, when you choose blue as a color, you don’t need to repeat UIColor, making the code more concise.

cardView.backgroundColor = .blue

Color Literal

Except for black and white, the preset colors are not very good-looking. Blue, for example, is oversaturated. Sure, we can initialize UIColor with RGBA, but you have to divide by its maximum value. In this case, it’s 255.

cardView.backgroundColor = UIColor(red: 255/255, green: 45/255, blue: 85/255, alpha: 1)

Color Literal allows you to set a color using the GUI. By typing Color Literal, you’ll get the autocompletion for that. Then, just double-click to pick the color.


Corner Radius

Every object is a UIView. The UIView has a layer property that allows you to set additional properties such as rounded corners, shadows, etc.

cardView.layer.cornerRadius = 14

Drop Shadows

To add a shadow, you need to set the opacity, offset and radius.

cardView.layer.shadowOpacity = 0.25
cardView.layer.shadowOffset = CGSize(width: 0, height: 10)
cardView.layer.shadowRadius = 10

Renaming Label

Because we’re going to have multiple labels, we shouldn’t name it label, so that it doesn’t confuse with other labels. Let’s rename to titleLabel.

let titleLabel = UILabel()
titleLabel.frame = CGRect(x: 16, y: 16, width: 272, height: 38)
titleLabel.text = "Learn Swift 4"

Let’s also move the label to be inside the cardView. Just like how we have the cardView to be inside view (the View Controller’s background), we now have label inside cardView. It’s the same organization as the Groups in Sketch.



The Label can have a property called font, which enables you to set the typeface, size and weight. Let’s set it to system font, which is San Francisco by default, size 32 and weight Semibold.

titleLabel.font = UIFont.systemFont(ofSize: 32, weight: .semibold)
titleLabel.textColor = .white


The captionLabel will have a similar settings to the titleLabel. Let’s add Caption to the cardView.

let captionLabel = UILabel()
captionLabel.frame = CGRect(x: 16, y: 204, width: 272, height: 40)
captionLabel.text = "Design directly in Playground"
captionLabel.textColor = .white

Adding images to Resources

To use images in our Playground, you need to open the Navigator by pressing Command + 1. Then, drag and drop the image files found in the assets provided.



With UIImageView, you can use an image file and set its contentMode. Let’s set up coverImageView, with scaleAspectFill, which always make sure that the image covers the entire width or height, whichever is the highest, while keeping the aspect ratio. ImageView is basically a View that wraps around an Image. Now, let’s set the image inside.

let coverImageView = UIImageView()
coverImageView.frame = CGRect(x: 0, y: 0, width: 300, height: 250)
coverImageView.contentMode = .scaleAspectFill
coverImageView.image = UIImage(named: "Cover.jpg")

Image Literal

You can simplify the code by dragging and dropping from the Resources.


Clip To Bounds

You might have noticed that the cover image is larger than its cardView container. We need to use something like Mask in Sketch. In Xcode, you can use the property clipToBounds to create a masking. Then, set the rounded corners.

coverImageView.clipsToBounds = true
coverImageView.layer.cornerRadius = 14


Just like when you read a page, there is an order in how you process the information: from top to bottom. Code works the same way. If you insert the image after the texts, the program will think that the image sits on top of the texts. To fix this, you need to re-arrange the order of the code.


Background Image

Since this is a prototype, we don’t need to recreate the elements we don’t want to animate or modify. For the rest of the elements, we’ll just use an image that takes the entire screen and add that to the main view. Make sure that the backgroundImageView is added before cardView.

let backgroundImageView = UIImageView()
backgroundImageView.frame = CGRect(x: 0, y: 0, width: 375, height: 667)
backgroundImageView.image = #imageLiteral(resourceName: "Chapters [email protected]")


Your final Playground should look something like this. The code has been re-arranged a little to make sure that the hierarchy works as expected. Don’t hesitate to play with your code after this session. The best way to learn new lessons is by breaking the code and figuring out how to fix it afterwards.

So far, you’ve learned the basics of coding the UI objects in code. This is the initial setup we’ll need to start animating the card.


Animate in Playground

High-fidelity prototyping tools have become incredibly popular over the past years with FramerFlinto and Principle leading the way. What those tools allow you to do is to animate specific elements of your user interface.

If a picture is worth 1000 words, a prototype is worth 1000 meetings. —saying at Ideo

Prototyping is an essential skill to have. It has always been. If you look at how Apple build their products, you get a sense of how much they prototype everything, not just for their software but also for their hardware.


To follow this course, you can download the source file, which will help you compare your progress.

Prototyping in Swift

Personally, I consider prototyping a little differently. I don’t separate the process from actual development. I don’t like to add extra processes between design and development. After all, even if your prototype ends up looking great, you’re not actually reducing the build time. You may in fact add to it. Your developer may reject it, because understandably they have too much on their plate. They do 70% of the work, hence why iOS apps traditionally take 10x longer than Websites.

What if your prototype can actually be a real product?

Most designers today know how to build a Website. We can certainly apply the same attitude towards making apps, by learning Swift and Storyboard instead of CSS and Javascript.

Final Result

We’re building a simple transition from the Main screen to the Section screen. While Playground may not allow you to test on devices, the code that you create here can easily be transported to Xcode. We’re using Playground to get a firm grasp at some of the basic concepts of animating in Swift.


Open Playground File

We’re going to use the Playground file we created from Design in Playground. Basically, we have set up the basic UI elements from scratch, so that we can animate them here.

Animation Basics

iOS 11 and Material Design set new standards for animations. Now, we expect screens to transition gracefully from one to another. If you plan your animations carefully, you can transition multiple elements to end like the next screen’s beginning state.

How do you animate, you may ask? To understand some of the theory behind animation, I suggest heading to the Animations section. Basically, you need to set the beginning state and end state. The beginning state is our current view. The end state is the Section view.



Let’s look at the ** UIViewPropertyAnimator** class. This is just one of the many ways to animate in Swift. With this, you can move things, change colors and sizes and have complete control over the animation later. In the End state, we’ll make sure to align and resize the same elements, like the cardView, coverImageView, titleLabel and captionLabel.

Let’s type this after we set up backgroundImageView. Also, make sure that the Assistant Editor is open.

let animator = UIViewPropertyAnimator(duration: 0.7, dampingRatio: 0.7) {
    // End state



Set how long you want your animation to run. Typically, it would be somewhere between 0.5 seconds to 2 seconds. In this case, set the Duration to 0.7.


Spring and bouncing animations are used everywhere in iOS, so we’re going to replicate that with the Damping Ratio combined with the duration. The great thing about this technique is that it’s fully customizable. Let’s set the Damping Ratio to 0.7.

Animate Card

You can change the position, the size and other properties available to your UI object. New in Xcode 9, you can now animate the cornerRadius as well. In this animation, we want to expand the card so that it takes the full size of the screen. Make sure that the cardView has a white background.

Write this code in the animator, between the curly brackets.

cardView.frame = CGRect(x: 0, y: 0, width: 375, height: 667)
cardView.layer.cornerRadius = 0

Finally, outside of the curly brackets, we’re going to start the animation by referencing the animator that we created and use the startAnimation method.

DesignCode-Animate playground-Animator

Customizing the Animation

At this point, you can start customizing the springiness of the animation. If you wish to have less bouncing and overshooting, you can use duration 1, damping 1. If you want more, you can use duration 0.5, damping 0.5. The lesser the values, the more exaggerated the animation is going to be.

Animate the Cover

The Cover image will be animated similarly to the Card. It’ll take the full width, but the height will be limited to 420. Also, the rounded corners will be set to 0.

coverImageView.frame = CGRect(x: 0, y: 0, width: 375, height: 420)
coverImageView.layer.cornerRadius = 0

Animate the Labels

Since we have more space for our design, we’ll push the margins a little for our titleLabel and captionLabel. Instead of a 16 pt margin, we’ll use a 20 pt margin. Additionally, the captionLabel will be further down.

titleLabel.frame = CGRect(x: 20, y: 20, width: 374, height: 38)
captionLabel.frame = CGRect(x: 20, y: 370, width: 272, height: 40)

Description Label

In the Section screen, we’ll want to have a body text. Let’s create one right before we declared the animator.

let descriptionLabel = UILabel()
descriptionLabel.frame = CGRect(x: 20, y: 448, width: 335, height: 132)
descriptionLabel.text = "Three years ago, Apple completely revamped their design language for the modern users. It is now much simpler, allowing designers to focus on animation and function rather than intricate visual details."
descriptionLabel.textColor = .black

Add the descriptionLabel to cardView, right after captionLabel.


Number of Lines

Notice that our long paragraph of text is not showing everything. We’ll need to spread that over multiple lines of text. Let’s use the property numberOfLines.

descriptionLabel.numberOfLines = 10

Add Delay

As we preview the animation on the right, we can see that our animation is happening too fast at the beginning, so it’s really hard to follow what’s going on. Let’s add a slight 1 second delay at the beginning. This is completely optional and will need to be removed at the end of the tutorial when we use tap events.

animator.startAnimation(afterDelay: 1)

Fade In Animation

We can animate the opacity to give a nice fade in animation. Let’s set the descriptionLabel opacity to 0 at the beginning, and opacity to 1 at the end state.

Outside of the animator class, right below where you set up descriptionLabel.

descriptionLabel.alpha = 0

Inside the animator’s curly brackets.

descriptionLabel.alpha = 1


Once we reach the Section screen, we need a way to go back to the Chapters screen after the animation is completed. Let’s create a close button.

let closeButton = UIButton()
closeButton.frame = CGRect(x: 328, y: 20, width: 28, height: 28)

For the background color, we want to get a 50% black. Let’s use Color Literal and set it in the color picker.

closeButton.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.5)
closeButton.layer.cornerRadius = 14
closeButton.alpha = 0

One of the things that set buttons apart is that they have different states. As a result, we must use the setImage method and specify not only the image, but also for which button state. The normal state is the state that you see by default.

closeButton.setImage(#imageLiteral(resourceName: "[email protected]"), for: .normal)

When a user presses the button, we need to fire an event by using addTarget. Here, we’re firing the function ** closeButtonTapped**.

closeButton.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)

Close Tap Function

Since the Close Button is calling a function called ** closeButtonTapped, we’ll create that function outside of the **loadView main function. It’s right before the last closing curly bracket.

Notice that new in Swift 4, we must add @objc in front when calling from a #selector, which is what the error recommends us to do.

@objc func closeButtonTapped() {
    // Do something when user taps on close button

Moving Objects to Class

When you start referencing objects in the closeButtonTapped function, you’ll notice that the autocompletion doesn’t kick in. That’s because those objects were initialized inside of loadView, which is not inherited by closeButtonTapped. We need to move those object declarations at the root level of MyViewController instead, which then will be inherited by all functions inside.

For every object that we initialized, we’ll move them right before the func loadView.

let cardView = UIView()
let coverImageView = UIImageView()
let titleLabel = UILabel()
let captionLabel = UILabel()
let descriptionLabel = UILabel()
let backgroundImageView = UIImageView()
let closeButton = UIButton()


Using Self in a Nested Class

Class-wide objects can get conflicted with newly declared objects. For example, if you create a second object cardView in loadView, how do you differentiate between the two cardView?

let cardView = UIView()

In that case, you’ll need to be explicit and use self to specifically target the Class-wide cardView. Now self.cardView references the Class-wide object, but just cardView references the newly created object.


However, inside a nested Class, you cannot reference a Class-wide object unless you use self. So, inside our animator Class, we’ll have to use self for every object referenced.

let animator = UIViewPropertyAnimator(duration: 0.7, dampingRatio: 0.7) {
    self.cardView.frame = CGRect(x: 0, y: 0, width: 375, height: 667)
    self.cardView.layer.cornerRadius = 0
    self.coverImageView.frame = CGRect(x: 0, y: 0, width: 375, height: 420)
    self.coverImageView.layer.cornerRadius = 0
    self.titleLabel.frame = CGRect(x: 20, y: 20, width: 374, height: 38)
    self.captionLabel.frame = CGRect(x: 20, y: 370, width: 272, height: 40)
    self.descriptionLabel.alpha = 1
    self.closeButton.alpha = 1

Dismiss Animation

Now that all our objects are accessible Class-wide, we can finally reference them in the closeButtonTapped function. Let’s create the animation. Essentially, we need to set all the states back to their original properties before the first animation starts. You almost copy and paste the same properties found in the objects, before animation.

@objc func closeButtonTapped() {
    let animator = UIViewPropertyAnimator(duration: 0.7, dampingRatio: 0.7) {
        self.cardView.frame = CGRect(x: 20, y: 255, width: 300, height: 250)
        self.cardView.layer.cornerRadius = 14
        self.titleLabel.frame = CGRect(x: 16, y: 16, width: 272, height: 38)
        self.captionLabel.frame = CGRect(x: 16, y: 204, width: 272, height: 40)
        self.descriptionLabel.alpha = 0
        self.coverImageView.frame = CGRect(x: 0, y: 0, width: 300, height: 250)
        self.coverImageView.layer.cornerRadius = 14
        self.closeButton.alpha = 0

Tap Event

Currently, the first animation is triggered 1 second after the view is loaded. The real interaction that we’re looking for is to start the animation when the user taps on the cardView. For this to happen, we’ll need to use a UITapGestureRecognizer class, which will call a cardViewTapped function. Additionally, we’re going to attach the tap gesture to cardView, and set isUserInteractionEnabled to true.

let tap = UITapGestureRecognizer(target: self, action: #selector(cardViewTapped))
cardView.isUserInteractionEnabled = true

Present Tap Function

Let’s create the missing cardViewTapped function.

@objc func cardViewTapped() {
    // Do something when user taps on cardView

Move the Animator Code

Let’s move all our animator code from loadView to the cardViewTapped function. Make sure to remove the startAnimation delay.

@objc func cardViewTapped() {
    let animator = UIViewPropertyAnimator(duration: 0.7, dampingRatio: 0.7) {
        self.cardView.frame = CGRect(x: 0, y: 0, width: 375, height: 667)
        self.cardView.layer.cornerRadius = 0
        self.coverImageView.frame = CGRect(x: 0, y: 0, width: 375, height: 420)
        self.coverImageView.layer.cornerRadius = 0
        self.titleLabel.frame = CGRect(x: 20, y: 20, width: 374, height: 38)
        self.captionLabel.frame = CGRect(x: 20, y: 370, width: 272, height: 40)
        self.descriptionLabel.alpha = 1
        self.closeButton.alpha = 1


Using these techniques, you can create a fairly complex animation prototype using real production code that can be used by you and your developer.

Design in Storyboard

As a designer, to be able to implement your own design is empowering, not to mention fun as well. We’re fortunate to have a functional visual tool like Storyboard that even developers use. Not only can you prototype on it, but you can also create production-quality layouts that co-exist with production code.

It has come to a point where I find it easier to build an iOS app than a Web app. It’s all thanks to Storyboard.

It’s time to design an entire screen based on a design delivered. We’ll start with the Home screen. In this section, you’ll learn more in-depth on how to use all the objects you find in the Object Library.


To follow this course, you can download the source file, which will help you compare your progress.

UIView for Group

Let’s create the container for the Hero section. Usually, you want to use a UIView to group together a bunch of objects. Drag and drop the UIView and go to Size Inspector and change the properties to x 0y 0width 375 and height 452.


UIImage for the Background

Drag and drop a UIImage inside the UIView, and set it to the same properties: x 0y 0width 375 and height 452. Set the Image to Home and the Content Mode to Aspect Fill.


UILabel for Text

For the main title, we’ll drag in a UILabel. Double click on it and set the text to “Learn to design & code for iOS 11”. Set the color to white and Lines to 0. The size will be: x 30y 86width 160height 172.


The font can be changed by clicking on the T icon in the Attribute Inspector. Set the style to Semibold and size to 36.



For the phone image, we’ll drag in another UIImage. Set the size to: x 194y 25width 123height 319. Set the image to Art-iPhoneX.


Background Blur

The Storyboard’s Object Library has a lot of interactive objects such as buttons, text fields, date pickers, etc. One of them is the Background Blur layer, which is prominently used in iOS and can be replicated in Sketch.

We’ll drop in a Visual Effect View with Blur object and set to the following size: x 0y 322width 375height 130. The Blur Style is Dark.


Layer Ordering

Notice that the layers in the left are ordered the same way as Photoshop, or the opposite of Sketch. Layers in the back are further up, and layers in the front are further down.

Main storyboard %E2%80%94 Edited

Stats UILabels

At this point, we’ll create 3 labels to show the stats of the book. Set the first label to WATCH with properties: Color white, Medium 15 pt, x 30y 23width 58height 18.

Changing Color

For the Watch text, we’ll want to use a slightly opaque color. Clicking on the right part shows a list of preset colors for iOS. Clicking on the left part gives a custom Mac color picker and you can quickly change the opacity there. Set it to 60%.

Duplicating Object

You can duplicate by pressing Command + D to create the second label. Double-click to change the text to “44 hours”. The position is: x 30y 39. Set the font to Semibold 30 pt.

For the third text, duplicate again and set the text to “of video lessons”. The font will be: Medium 15 pt. Position: x 30y 75.

Size to Fit Content

At any point, you can wrap the bounding box against the text by going to Editor > Size to Fit Content. The keyboard shortcut is Command + =.


UIView for Line

Now, let’s create the 3 pt line below the stats. We’ll drag and drop a UIView object. Set the properties to: x 30y 105width 130height 3.

Rounded Corners with Runtime Attributes

To add a border radius to the UIView, we’ll need to go to the Identity Inspector and create a new User Defined Runtime Attribute.

In the Key Path field, write layer.cornerRadius. In Type, choose Number and in Value, write 3. Please note that Runtime Attributes won’t be reflected in Storyboard, but will be shown when you run the app in iOS Simulator.


Using a HEX color or Eyedropper

For the color of the line, you can go to the color picker and click on RGB Sliders to find the Hex Color # field. Paste the HEX color value AF47B9.


Multiple Selections and Duplicate

Next, we’ll select all 4 objects by holding Shift. Once selected, Option + drag to duplicate to the right. Make sure to use the smart guides (blue lines) to align perfectly. Hold Option to view the distances from the left and use the arrow keys to nudge those objects until you get a 195 from the left.

Change the duplicated texts to: SEARCH50,000words and images.


Creating a Circle

For the Play Video background, we’ll first need a blurred background wrapper. Drag and drop a Visual Effect View and set it to x 226y 148width 50height 50. Go to Identity Inspector and set a new Runtime Attribute layer.cornerRadius, type number, value 25. The value to get a perfect circle is the width divided by 2.

Because the Visual Effect View has a sub-View, we need to enable Clip to Bounds in the Attributes Inspector. This is the equivalent of Mask in Sketch, which enables you to ensure that any sub-elements don’t appear outside of those bounds.


UIButton for Play Button

Drag and drop a UIButton inside of the Visual Effect View. Double-click on it to delete the text inside. Go to the Attributes Inspector, set the Image to Action-Play-Small. Set the size to x 0y 0width 50height 50.

UIView for Book Container

Let’s create a container for the book content. Drag and drop a UIView with the properties: x 0y 452width 375height 348. Grouping similar objects makes it easy to move and set up constraints later.

Media Library

For the book image, we’ll drag and drop directly from the Media Library. What’s great about this technique is that the asset gets perfectly sized from the start. You just need to center horizontally and set it at a distance of 50 from the container. Again, use the Option key to view the distances between elements.

Adding Drop Shadows

Let’s add a drop shadow to the book. Select the book and go to the Identity Inspector. In Runtime Attributes, add the following:

layer.shadowOpacity, Number, 0.25
layer.shadowRadius, Number, 10
layer.shadowOffset, Size, {0,0}

Because an image dropped from the Media Library has Clip to Bounds enabled automatically, we need to disable this in order to show the drop shadow.

Naming Objects

Typically, objects inherit their properties. For example, a Label gets the name of its text property. But for UIViews that serve as containers, we can give them a custom name by going to the Identity Inspector and change the Label property. For the first Hero container, let’s name it Hero View and for the book container, let’s name it Book View. Again, it’s good to be specific of the type of object it is by adding View at the end.



So far, we’ve learned how to use basic objects in Storyboard such as views, buttons and images. On top of that, we got familiar with distances, smart guides and runtime attributes. We have yet to set constraints for adapting our layout, which is what we’ll learn next.

Auto Layout

With Auto Layout, Stack Views and Size Classes, you should have everything you need to build a truly adaptive layout that works across devices. We’re going to learn how to apply dynamic constraints in order to make them adapt to any screen size.


To follow this course, you can download the source file, which will help you compare your progress.

Previewing your Layout

If you click on “View as: iPhone 8”, you’ll see a list of devices you can design on. As you can notice, the layout doesn’t adapt well to the iPhone 8 Plus or the iPad. We need to apply Auto Layout to make the content adaptive to any device.


Position and Size

Auto Layout requires 2 things: position and size. As long as you set those constraints, Auto Layout will be happy. There are 2 ways to respect those requirements: Align and Pin.

Align allows you to center things and align elements with each other. Pin lets you set the size and the spacing from the edges of a container.


First Rule of Auto Layout

The first rule of Auto Layout is that all new constraints must be against an element that already has known position and size. For example, the Superview, which is the root screen size, already has a position (x 0, y 0) and size (375 x 667 for iPhone 8) known to Xcode. So, when you Pin or Align against the Superview, Auto Layout will work perfectly.

On the other hand, if you Pin or Align the Hero View against the Book View, Auto Layout will give you warnings, since the Book View doesn’t have any constraint set up.


Add New Constraints

Before applying any constraint to inner elements, we need to make sure that containers are properly set up against the Superview. Without knowing the position and size of the container, any constraint set to the title, phone or play button will be ambiguous.

For the Hero View, let’s click Add New Constraints and set to 0 for the topright and left constraints. Also, set the height to 452. With this, Auto Layout has enough information about its position (x, y) and size (width, height).

From those constraints, it knows that the Hero View has the same position (x 0, y 0) as the Superview. Then, thanks to the left and right constraints, it knows that the width is 375 on the iPhone 8, and is adaptive to the screen width. Finally, we manually set the height to 452.


Book View Container

For the Book View, we’ll set the values to 0 for the topright and left constraints. The height will be manually set to 348. With this, our 2 containers have constraints. This means that we can start setting up constraints for the objects inside them.


Home Image Constraints

Let’s do the Home image constraints before the titles, since it’s much simpler. The Home image needs to take the full width and height of the Hero View. So we’ll Add New Constraints to 0 for toprightbottom and left. This effectively satisfy both position and size.


Centering with Offset

For the title, we want to center it both horizontally and vertically, but with an offset. Otherwise, it will overlap with the device image.

First, click on Add New Constraints and set the width to 160 and height to 172. Then, click on ** Add Constraints** . Click on Align and check both Horizontally in Container and Vertically in Container. This will automatically center the bounding box.

As expected, it overlaps with the device image. That’s not what we want. To add some offset, we can go to the Size Inspector and change to the initial values: x 30y 86. Like this, there is enough negative spacing between the title and the device image.


Resolve Auto Layout Issues

Now, since the constraints are different from the values entered manually, Auto Layout will show a conflict. Auto Layout will make an assumption based on your constraints, as shown by the yellow dotted lines. You can solve the conflict by clicking on Resolve Auto Layout Issues which is next to Add New Constraints. Let me explain a little bit on the 4 options presented.

  • Update Constraints: you think the yellow dotted lines are incorrect. Clicking this will adjust the constraints based on the values changed.
  • Add Missing Constraint will add whatever is missing in term of position or size.
  • Reset to Suggested Constraints will reset the constraints and let Auto Layout add new ones from scratch.
  • Clear Constraints will remove all constraints.

All 4 of these options can specific to a single object or can apply to all objects on the screen.

Finally, you have the Update Frames icon at the far left. Use this if you think that the yellow dotted lines are correct and want the object to move exactly there.


Updating Constraints for Title

In this specific case, we want to update the constraints to follow the values we’ve set manually. Click on Resolve Auto Layout IssuesUpdate Constraints. This will effectively add the offsets of -77.5 from center X and -54 from center Y.


Device Image Constraint

The device image’s position is entirely dependent on the position of the title. We’d like to center it against the title, so that if the screen is bigger, it’ll center nicely. First, we need to set the width constraint to 123, and height constraint to 319.


Constraints Between Two Objects

Two objects can have a constraint against each other. You can center objects together, align them or give them equal widths or heights. To set a constraint between two objects, Control + Drag from the device image to the title. While holding Shift, select Horizontal Spacing and Center Vertically. This allows you to enable multiple constraints at once.

Let’s change the y position back to 25 and select Update Constraints.


Set Constraints in Document Outline

The play visual effect view simply needs to be centered against the device image. Since it’s hard to select it without selecting the UIButton, we’ll do it in the Document Outline instead. Control Drag from the Visual Effect View to the Art-iPhoneX and select Center Horizontally and Center Vertically while holding Shift. Then, add the width and height constraints to 50.

Set the position back to x 226 and y 148, and click Update Constraints.


Play Button Constraints

For the play button, we simply need to Add New Constraints to 0 for toprightbottom and left. This will satisfy both position and size.


Stats Visual Effect View

For the statistics container, we’ll set 0 for the rightbottom and left constraints. Also, we’ll set the height to 128.

Stack View

Stack Views allow you to group together similar objects to apply automatic constraints based on the object type and its container properties. Instead of manually setting a bounding box for each object, you configure the AxisAlignmentDistribution and Spacing to all objects inside the Stack.

Select the 3 labels and line view and click on Embed in Stack. Once embedded, they all share the same Stack properties. Additionally, the Stack dynamically wraps around the objects in a way that respects the Alignment, Distribution and Spacing. It even makes it taller than we’d like.

Let’s add a top and bottom constraint of 20, with a width of 130 to the Stack. Also, you’ll notice that the line view takes the entire height of the box. To fix this, you can set a height constraint of 3 to it.


Stack View Distribution

Our Stack View doesn’t seem to be distributing the content properly. The bigger title takes way more spacing than the line view, for example. We can fix this by playing with the different Distribution properties: FillFill EquallyFill ProportionallyEqual SpacingEqual Centering. Let’s set to Equal Centering, since this looks like the closest to what we have to the original design.


Second Stack View

Let’s repeat the same Stack View steps for the second column of labels and line view. Select the 4 objects and click on Embed in Stack View. Then, select the line view and set the width to 130 and height constraint to 3. Finally, set the Stack View Distribution to Equal Centering.


Horizontal Stack View

Stack Views can be stacked as well. Let’s select the 2 Stack Views and stack them together. Since they’re positioned left and right, it’ll automatically set the Axis to Horizontal this time.

Since we want to center our content horizontally, we’ll click on Align, and set to Horizontally in Container. Then, we’ll set the constraints to top 20, bottom 20 and width 300. Next, let’s change the Distribution to Equal Spacing.


Book Image Constraint

We want the book the center horizontally and have a fixed spacing of 50 from the top.

Let’s click AlignHorizontally in Container. Then Add New Constraints with top constraint to 50.


Size Classes

This neat tool allows you to set specific Auto Layout constraints and content based on groups of devices. It looks confusing at first, but it makes total sense once you know how to use it.

There are 3 settings for each orientation: AnyCompact and Regular.

  • Any x Any will apply to every device.
  • Compact x Regular will apply to all iPhone in portrait.
  • Compact x Compact will apply to all iPhones in landscape, except for the iPhone 8 Plus.
  • Regular x Regular will target the iPad in both portrait and landscape, except when in Split view.
  • Otherwise, Size Classes will tell you which devices are being targeted.

Use this illustration to see which ones are Compact or Regular.


Vary for Traits

You can use the Vary for Traits feature to apply constraints for specific Size Classes. To do that, select any device and click on Vary for Traits. Then, choose width or height.

For example, if you choose iPad and select width, it means that you’re applying constraints specific to Regular x Any, since the iPad has a Regular width trait. When you select the drop-down device, you’ll see all the devices that these constraints will target.


New Stats Column only for Regular Width

Let’s add a new column just for devices that have a Regular width. Select View as iPad (wR hR) and click Vary for Traits. Choose width.

Option Drag a Stack View in the Document Outline and release right below the Stack View. This will create a third column. Now select the wrapping Stack View and go to Size Inspector to double-click the Width equals 300 constraint. Click on the + icon next to 300 and press on Add. Type 450 next to the wR field. Change the text to: DOWNLOAD10GBof source files. Finally, click Done Varying.

This will show the third column on devices that has a Regular width.


Editing Constraints

Now, if we preview our layout, we’ll notice that it reacts beautifully across all devices. The only minor adjustment is the left constraint for the title on the iPhone SE, which is a little too near to the border.

There are 3 ways to edit the constraints.

  1. With the layer selected, you can find all the constraints in the Size Inspector.
  2. In your View Controller, you can also click the lines directly and edit them in the Size Inspector.
  3. Finally, the constraints can also be found in the Document Outline.

Let’s select the title and double-click the Align Center X constraint and set it to -70 instead.


Relation and Priority

I won’t go too much into detail about these advanced Auto Layout techniques, but it’s good to be aware of them. You probably won’t need them as much. When you edit a constraint, you can double-click it in the Size Inspector.

  • Relation: you can set a constraint to be Less Than or EqualEqual or Great Than or Equal. This is useful for dynamic content that can expand. With this, you can give them a minimum or maximum size. It’s sort of the equivalent of min-width and max-width in CSS.
  • Multiplier: you can also set a multiplier. This is useful to set an object to be half the size of another for example.
  • Priority: when you have potentially conflicting constraints, you can use Priority to give more importance to some.


Our layout is now completely adaptive for the iPhone and iPad in both landscape and portrait modes. Combining Auto Layout, Stack Views and Size Classes will enable you to create layouts that work across current and future device resolutions.

Adapting for iPhone X

The iPhone X introduces the need to follow the Safe Area layout guides. The Safe Area ensures that your content won’t be hidden by the Notch or corner radius. In general, background elements such as background images and colors should follow the Superview while the content such as labels, avatars and medias should follow the Safe Area.


To follow this course, you can download the source file, which will help you compare your progress.

Safe Area Layout Guides

The Safe Area is enabled by default in Xcode 9 if you start a new project. As you can see from this illustration, the red area is your Safe Area where the Notch, corners and Home Indicator won’t clip your content.


Preview on iPhone X

To design for iPhone X, the first thing we need to do is to set View as: iPhone X. Like this, we can see how our screen looks with a Notch and with large corners visible. Already, we can see that the device image is being slightly clipped by the Notch.



The content is often larger than the screen height, so scrolling is a key experience in iOS. Virtually all screens are wrapped in a UIScrollView. For the iPhone X, it’s important to set the border constraints against the Superview and not the Safe Area, because often times, you’ll want the background image to be underneath the Notch or the corners of the screen.

Let’s drag and drop a UIScrollView from the Object Library to the Document Outline, right below the Safe Area. Let’s set the Size to x 0y 0width 375height 812, which happens to be the size of the iPhone X screen.


Wrapping In Scroll View

We’ll need to put the Hero View and Book View to be inside the Scroll View so that it can be scrolled vertically should the content height exceed the screen height. Drag and drop both the Hero View and Book View inside Scroll View.

Then, select Hero View and set the size y position to 0. Select the Book View and set the y position to 452.


Add Missing Constraints

Thanks to these placements, Xcode will be smart enough to detect the missing constraints. Check the Auto Layout warnings by clicking on the red arrow in the Document Outline. Start Adding Missing Constraints one by one by clicking on the red square icon until you no longer have Auto Layout issues.

Keep in mind that this feature is not perfect. It may in fact add some unwanted constraints, but it really helps that we added a lot of important constraints manually.


Fixing the Device Image

Let’s fix the clipping on the device image. Since the device image is relative to the y position of the title, we’ll change the title. By doing that, it will affect both the device image and the play button inside.

Select the title and double-click on the middle line. You’ll find a popover where you can change the -54 value to -34.


Text with Multiple Lines

Drop a UILabel below the book and set the text to “An interactive book on how to design and code an iOS 11 app.”, at 22pt Medium color 404040. When you have multiple lines, you need to set the Lines property to 0, which means that there can be an infinite number of lines. Set the Alignment to center. Additionally, set the size to x 30y 220width 315height 53.

Let’s duplicate the label and set the text to “For beginners and designers.”. Change the color to Light Gray Color by clicking on the right side of the Color property.

For the first label, control drag to the book image and select Center Horizontally. Set the constraints to top 20 and width 315.

For the second label, control drag to the first label and shift select Center Horizontally and Equal Widths. Set the constraint to top 0. Make sure that the constraint is against the first label and not the book with the arrow. Automatically, the bounding box for the labels will wrap around the expected size of the text.


Custom View Controller Size

The content for our Home screen is getting larger than the viewable portion. To make it even taller than the iPhone X, select the View Controller and go to the Size Inspector. There, you can set the Simulated Size from Fixed to Freeform. Set the height to 2000.


Chapter View Container

It’s time to create the Chapter section where the Safe Area layout guides will be truly useful. Let’s create a UIView with x 0y 800width 375height 380. Set the background color to F5F5F5. Change the name to Chapter in the Identity Inspector’s Label field.

Set the constraints to 0 top0 right820 bottom and 0 left. Afterwards, we’ll need to resolve the conflicting constraints by deleting the one that makes the least sense: bottom = Book View + 12. It’s confusing at first to keep track of all the constraints, but once you get the hang of it, you’ll know quickly which constraints don’t belong.

Finally, add the recommended missing Y constraint to the Scroll View.


Chapter Title Label

For the title, create a UILabel with text “CHAPTER 1: 12 SECTIONS”. Set the font to Semibold 15 pt, color 404040. Set the constraints to top 50right 20 and left 20.


Chapter Section View

Let’s create a card UI for each section. Drop a UIView and set the constraints to left 20bottom 50width 304height 248.


Testing on iPhone X

It’s important to constantly test your interface on the iOS Simulator or the device. To do that, select iPhone X and click on the Play button in Xcode (Command R).


Fixing the Status Bar Background

Some visual problems won’t be noticeable in Storyboard but will be obvious when testing. For example, as you scroll back up, you’ll notice that there is a big white space. To fix this, select the Scroll View and go to the Size Inspector to change the Content Insets to Never.


Enabling Safe Area Layout Guide

We also need to fix the Chapter content to have more margin on the iPhone X’s landscape mode. The Safe Area layout guide is perfect for solving this problem. By default, the layout guide is enabled at the Superview level, but not in subviews. To enable the guide, select Chapter View and go to the Size Inspector and check Safe Area Layout Guide.


Safe Area Constraint

Now we need to fix the left constraint for both the Chapter title and view. Select the title and click on the blue line on its left. Then, in the inspector, change the Second Item from Chapter View.Leading to Safe Area. Let’s do the same for the view’s left constraint. Change to Safe Area as well.



Designing for iPhone X is all about anticipating how the Notch, corners and Home indicator will affect your design. At the top of the screen, we pushed the device image down a little and we applied the Safe Area layout guide to our Chapter content. In addition, we learned how to continuously test our app on the iPhone X device. Now, our design works perfectly on the iPhone X’s portrait and landscape mode.

About the Author

Leave a Reply

Your email address will not be published. Required fields are marked *

You may also like these