Create an IBDesignable UIView subclass with code from an XIB file in Xcode 6

by Paul Solt


Many times, I find myself wanting the visual power of both design and layout from Xcode 6’s new interface builder. I’m a visual person, and sometimes I like to create custom UIControl or custom UIView objects that can be reused.


You can create a custom UIView subclass and load the interface from an XIB file. In Xcode 6, you can also go a step further and provide design time visualization and customization in Xcode’s Attributes Inspector.

This is a big deal if you’ve ever loaded an XIB file from code and attached it to a user interface. In the past, you could block out the colors of the UI, but you could never see the composition. You also couldn’t change any of the parameters at design time within your main Storyboard or XIB file.

Custom UIView Subclass (e.g.: CustomView)

These are the steps to making a custom UIView that is designable within Xcode:

  1. Create a View .xib file (e.g.: CustomView.xib)

  2. Design the user interface in Xcode

  3. Set up Auto Layout constraints

  4. Create a Swift code file (CustomView.swift)

  5. Set .xib file’s “File’s Owner” custom class to CustomView (it must match the class name)

  6. Implement both CustomView initializers: init(coder:) and init(frame:)

  7. Load the UIView from the .xib file using the NSBundle and UINib classes

  8. Add the view as a subview and property for the class (future modifications)

  9. Add autoresizing masks for the view to match the size of the CustomView itself

  10. Make the view’s frame leverage the design time size of the embedded CustomView’s bounds

Note

If you leverage any image assets, you’ll want to make sure they are in the same bundle as the custom view. This is especially important when trying to leverage extensions or static libraries.

Visual Guide for a custom UIView from an XIB file

In the following steps I will visually show and explain what you'll need to do to create an IBDesignable and IBInspectable UIView that you can reuse in your iPhone apps. You will be able to leverage the power of design time editing in Xcode along with a better visualization of what your app will look like.

1. Create a View XIB file (e.g.: CustomView.xib)

The first thing you'll need is a new user interface file called an XIB or .xib or nib file. This is like a storyboard file, but it only holds a single UIView object.

Create a new file from the Menu bar using File > New > File or the keyboard shortcut Command + N:

Select iOS > User Interface > View; name it “CustomView” and add it to your target:

2. Setup the UIView for a custom size and disable the status bar.

The UIView will initially be setup for a full-screen iPhone view with a standard size and a status bar. You'll need to make some adjustments to use a smaller size.

Set the Size to “Freeform” and the Status Bar to “None:”

3. Design the UI for your custom control or widget

Leverage the power of Xcode to drag and drop the UI elements for your custom widget. Drag out buttons, labels, image views, and anything else that you want to display in the custom view.

4. Connect Auto Layout constraints to control layout

Depending on how your control is going to be used, you will want to setup constraints that either keeps the size fixed or make the control adaptive to larger interfaces.

You can select all of the UI elements to see if the connections are good. Blue = good, orange = missing constraints, and red = conflicts. Using constraints you need to establish the rules to set the width, height, and position of every UI element.

Auto Layout enables the relative layout of visual elements in your iOS app:

5. Create a Swift code file to drive the custom UIView or UIControl

You need to connect the XIB file to a Swift code file in order to provide the brains or logic to power the UI element. You'll be creating actions and outlets that will be used to change the visuals or respond to input.

Create a new code file using File > New > File > iOS > Source > Cocoa Touch Class:

On the next screen, subclass the UIView class and choose Swift:

6. Connect the XIB file and the Swift code file together using the “File’s Owner” attribute

The XIB user interface file will be loaded when the view is ready to display on your iPhone. In order for it to work with your code file, you'll need to make it aware of what Swift file is going to preform all the logic.

On the right panel, set the Custom Class name to the same name as your Swift code and XIB file:

7. Add code to load from a .xib file using the NSBundle and UINib classes

I wish the tutorial could end here. Unfortunately, Apple doesn't provide an easy way to connect the UI you designed to your UIView subclass. To connect the two, you are going to write some code that will load the user interface and place it inside the edges of the view in code.

Create two methods to load the .xib file from the bundle in which it’s located:

// Our custom view from the XIB file
var view: UIView!

func xibSetup() {
    view = loadViewFromNib()

    // use bounds not frame or it'll be offset
    view.frame = bounds

    // Make the view stretch with containing view
    view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight

    // Adding custom subview on top of our view (over any custom drawing > see note below)
    addSubview(view)
}

func loadViewFromNib() -> UIView {
    let bundle = NSBundle(forClass: self.dynamicType)
    let nib = UINib(nibName: "CustomView", bundle: bundle)

    // Assumes UIView is top level and only object in CustomView.xib file
    let view = nib.instantiateWithOwner(self, options: nil)[0] as UIView
    return view
}

You need to add a property to store the view that will be loaded from the XIB file. It might seem a little odd to store a view as a property within a UIView object. A custom UIView is just a composition or hierarchy of UIView objects that use position, size, color, and images to create the final look.

You'll also add two methods that will assist with the following step.

The first method, xibSetup() will be called from the initializers in the next step, when the UI is loaded. The loadViewFromNib() method will do the complex loading work from the file system.

8. Implement the initializers and leverage the code to load from an .xib file

Leverage the common code in both initializers used in UIView creation using your xibSetup() method.

You must make sure to call the super methods so that the correct UIView initialization occurs. The init(coder:) is called when creating your view within another interface file. The init(frame:) is called when creating your view programmatically (see below).

override init(frame: CGRect) {
    // 1. setup any properties here

    // 2. call super.init(frame:)
    super.init(frame: frame)

    // 3. Setup view from .xib file
    xibSetup()
}

required init(coder aDecoder: NSCoder) {
    // 1. setup any properties here

    // 2. call super.init(coder:)
    super.init(coder: aDecoder)

    // 3. Setup view from .xib file
    xibSetup()
}

9. Add a new UIView object to your Storyboard file and set the Custom Class name

Drag a UIView object onto the Storyboard canvas for your current View Controller. Resize the UIView element to fit a smaller portion of the app screen. Note: If it’s the first object you add, it’ll be huge.

Temporarily, change the UIView color to non-white, so you can see it:

To get the Storyboard to load the correct UI element, you'll need to set this "blank" UIView to act as the placeholder for your custom class. Doing so will trigger the init(coder:) method to create your custom UIView at run-time. You can learn more about this process by reading the top description from Apple's UIView Reference or the UIViewController Reference (click "more..." to read the hidden description).

You will need to change the class name to “CustomView” in the Identity Inspector:

10. Make the CustomView.swift file IBDesignable

At the top of your Swift code file, you need to add @IBDesignable in Swift. Xcode will now compile (takes a few seconds) and embed your custom UIView inside a Storyboard file.

import UIKit

@IBDesignable class CustomView: UIView {

}

11. Click on/off Main.storyboard to get Xcode to refresh your custom UIView

You should be able to make changes to your CustomView and see the changes in the Storyboard. Sometimes this can be buggy, especially if there is an issue. To force an update you can click on/off the Storyboard file, or you can use the new menu bar option described below.

An easier option is to select the Storyboard file and click on a custom view that's breaking. In the menu bar, do the following:  

Editor > Debug Selected Views

OR

Editor > Refresh All Views

Tip: Watch a video on how this works in Xcode 6.1.1

12. Add IBOutlets and IBActions to connect code and UI together

To work with any of the UI in code you must make connections with Outlets and Actions.

Open the Assistant Editor and then you can right-click and drag from the user interface into the associated code file. Create outlets for any UITextField, UIButton, or UILabel if you need to change the text. If you have a button, you'll need to setup an action to invoke a method using  the style buttonNamePressed(sender:).

You should have a set of outlets and actions like the following:

@IBOutlet weak var label: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var button: UIButton!
@IBAction func buttonPressed(sender: AnyObject) {
    // do something
}

Note: If you display an image, the UIImageView will need clipToBounds set to true to prevent artifacts and overdrawing.

13. Make an IBInspectable attribute to change the image at design time

The IBInspectable property allows you to expose functionality in code that can alter the appearance of the custom UIView. You can expose properties that are either computed, which gives you a hook to update the appearance.

Add code to alter the image using a computed property around the imageView outlet:

@IBInspectable var image: UIImage? {
    get {
        return imageView.image
    }
    set(image) {
        imageView.image = image
    }
}

14. Change the image at design time using the Attribute Inspector property

You can alter the appearance or settings for your custom UIView by changing parameters in the Attribute Inspector. Any property that you tag with @IBInspectable will be visible at the very top of the list of settings.

Change the text or even a corner radius using a computed property and the view.layer.cornerRadius value.

Resources

  1. Custom UIView with IBDesignable Elements - Apple’s Objective-C Code Sample
  2. Building Custom UI Elements With IBDesignable and IBInspectable - Think and Build
  3. How to Build a Custom (and “designable”) Control in Swift - Think and Build
  4. Debugging Xcode Live Rendering - Morten Bogh
  5. Nib Designable - Xcode Live Rendering With Nibs Made Easy - Morten Bogh

Summary

You can use this technique to create your own UIControl subclasses, just like UIButton or UILabel. UIControl provides the Target/Action model of interaction that allows you to create buttons, sliders, and more.

Using @IBInspectable you can also provide computed properties that can be changed using the Attributes Inspector at design time (convenient for non-programmers).

Connect

  1. Share this post on Twitter

  2. Let me know how you use it at @PaulSolt

  3. Checkout my Swift iPhone app courses

  4. Download the source code on github


Two weeks of a Swift Course and Two Apps on the App Store

by Paul Solt in


Alexandre started the Swift and iOS 8 Apps in 31 Days course and already has two apps on the App Store. Learn about his background and how he's spent his time learning to program new iPhone apps in Swift.

I have found his work to be very inspiring and I hope that you join me in making and selling your first iPhone app.

Not only has he submitted multiple apps to the App Store, but he's also been blogging about the process, struggles, and accomplishments. If you want to learn, this is one of the best ways to get started.

Learn about Alexandre's programming experience and work ethic.

What's your work/education background?

I have a French management business school degree. I'm an entrepreneur; in 2000 I built a recruiting agency in the information technology field.

In 2009, with two partners we created a software company that developed recruitment software in the cloud.

I'm in charge of the sales department.

When did you start programming in Swift? 

I started programming in Swift on September the 20th, after Apple released Xcode 6.0 

Did you have any programming experience before starting Swift?

I have a little experience in Python (our developer team works in Python, so I’ve learned the language to be able to understand them). A long time ago, I played with my HP48 calculator in a language similar to Pascal.

How much time have you spent each week working on programming?

I was really invested in learning Swift and I’ve spent ten to fifteen hours each day for three weeks to catch up on the iOS Developer.

Now I spend four to five hours a day working with Swift.

What do you recommend to other students who are learning Swift?

I would recommend coding their own projects while learning on good materials. I've found it very effective to follow great courses/learning resources and mix that with my own code at the same time.

Watching a video or reading a tutorial is great, but it will bring all its power if you try to make something on your own with that new knowledge. 

Did you have any issues or problems when you were learning Swift?

The main issue was before the beginning, when I tried to picture the amount of things to learn (the language, its concepts, Xcode, Cocoa, etc., etc.). It could be overwhelming.

But "the goal is the way." If you start with a good teacher, it is not about the mountain to climb but about the next step to take.

One step at a time on the right road and everything begins to feel accessible. It is a great journey and a lot of fun. 

How many apps have you submitted to the App Store?

I have two apps on the App Store.

Table Plan

Table Plan

Table Plan was a development to test if I could build an App. It was a nice learning project because it dealt with math (ellipse), gestures, popover and access to the address book. I'm happy to have published the app, because my mother uses it now. :)

Casual Poet

Casual Poet

Casual Poet is the result of the first App Challenge. It was an insane weekend of development (near forty hours of work in two days). But what a pleasure at the end to have something that looked like a complete App.

It’s more of a proof of concept right now, and it needs more developments to become a real game. I'm working on it now. 

Do you like making apps? What's your goal?

Making apps is really fun and rewarding. It is like a painting: at the end we have created something.

I want to take time to give back to the Swift community too. I've started a blog to share some coding topics I encountered during my developments that could help other developers.

My goal is to continue learning and build great apps. I'm really exited with the Apple Watch. Next year will be a great coding year.

The next step will be to release an App with a high level of quality and a profitable economic model.

Final Words

Awesome Thanks for all the insight into making apps with Swift! Follow Alexandre on Twitter or read his Swift programming blog!

Connect


Return Type Error Messages are Wrong in Swift

by Paul Solt in


Error messages from Xcode have a tendency to be wrong. A bad error message can send you searching in the dark in the wrong direction.

I want to share my process for searching for answers using Google and strategies that you can leverage in code to help you overcome some obstacles with Swift’s error prone error messages.

It seems that I find more wrong error message in Swift than from my experiences with Objective-C. However, that could also be attributed to my ability to fix common errors before Xcode had time to tell me what it thought was wrong in Objective-C.

I do know that I learn the most when I encounter errors and figure out how to fix them. As a beginner programmer, you will need to start identifying errors as you type them, or after Xcode points out an error message.

I’ll show an example using an error message that had me stumped, until I revisited it the next day.

Swift Compiler Error

/Users/paulsolt/Downloads/Word Magnet/Word Magnet/ViewController.swift:173:12: Cannot invoke 'init' with an argument list of type '(x: $T4, y: $T9)'

Code

func randomInt(number: Int) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomInt(number: CGFloat) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomPointInRectangle(rectangle: CGRect) {
    // Attempt 1
    return CGPoint(x: randomInt(rectangle.size.width), y: randomInt(rectangle.size.height))
} 

Ok, can you guess what’s wrong?

Google to the Rescue

I didn’t find the error message helpful, so I resorted to Googling it. Search the error message, and remove the file path and line numbers.
You can open the Issue Navigator and then right-click on an error to copy the error message to a web search bar.

Search 1

Cannot invoke 'init' with an argument list of type '(x: $T4, y: $T9)’

Nothing sticks out to me on this first search. I see MIPS assembly results from the $T4 and $T9, which look like hardware registers from assembly language. That won’t help you.

Search 2
Some of the error message is error specific, and doesn’t search well. Let’s cleanup the search text.

  1. You’ll need to remove the uniquely identifying information highlighted in bold. 
  2. Add Swift to the front of the search term. 
  3. Remove the single quotes.
Cannot invoke 'init' with an argument list of type '(x: $T2, y: $T5)’

becomes

Swift + Cannot invoke with an argument list of type (x: , y: )

The first result is good, but it’s not going to help us. It’s not the real problem that you have here. The first result is actually related to the reason I started writing this code.

http://stackoverflow.com/questions/24108827/swift-numerics-and-cgfloat-cgpoint-cgrect-etc

With two searches and you are still not understanding what is wrong. That’s normal when you first start programming. The results we found are relating to mixing Double, Int, and CGFloat types together, but that’s not the problem we’re facing.

What to do when Google Fails?

Next step when I have an issue like this is to try rewriting the line of code in a different way. You can write code that’s more verbose and that does less work on a single line of code. Separate complex statements into a separate lines of code.

Make a hypothesis and test it

Maybe there is something wrong with the randomInt() function, lets use just a number.

Workflow Tip

  1. Copy and paste the offending line of code.
  2. Comment out the first line, and alter the second line of code.

Swift Compiler Error

/Users/paulsolt/Downloads/Word Magnet/Word Magnet/ViewController.swift:174:12: Cannot invoke 'init' with an argument list of type '(x: IntegerLiteralConvertible, y: IntegerLiteralConvertible)'

Code

func randomInt(number: Int) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomInt(number: CGFloat) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomPointInRectangle(rectangle: CGRect) {
    // Attempt 2
    //    return CGPoint(x: randomInt(10), y: randomInt(10))
    return CGPoint(x: 10, y: 10)
} 

The error message is a little different, but very similar. Swift is still having an issue with the init method for the CGPoint. 

Break apart lines of code into multiple steps

What happens when you separate the CGPoint initialization from the return statement?

Swift Compiler Error

/Users/paulsolt/Downloads/Word Magnet/Word Magnet/ViewController.swift:176:12: 'CGPoint' is not convertible to '()'

Code

func randomInt(number: Int) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomInt(number: CGFloat) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomPointInRectangle(rectangle: CGRect) {
    // Attempt 3
//    return CGPoint(x: randomInt(10), y: randomInt(10))
//    return CGPoint(x: 10, y: 10)
    let point = CGPoint(x: 10, y: 10)
    return point
} 

Notice how the error message has changed?

Search 1

'CGPoint' is not convertible to ‘()’

The search results aren’t very conclusive, nothing seems to show up that’s related in the first set of results. Let’s try a different approach.

Search 2
google.com will strip a lot of special characters, let’s alter the search and try it on DuckDuckGo.com

"CGPoint is not convertible to ()” 

The search returns one related result, and it’s the solution to our problem.

https://duckduckgo.com/?q=%22CGPoint+is+not+convertible+to+%28%29%22

Swift Language Programming Guide

Reading or skimming the programming guide on Swift can also help you identify problems. If you’ve never coded before I’d recommend to type in some of the examples as you read, or you can take my online Swift courses.

If you read the Swift Language Programming Guide on Functions, you might have a vague idea of what the error is. Upon seeing the error I remember back to something I read in the book.

Strictly speaking, the sayGoodbye function does still return a value, even though no return value is defined. Functions without a defined return type return a special value of type Void. This is simply an empty tuple, in effect a tuple with zero elements, which can be written as ().

What Xcode is trying to tell you is that it cannot convert a type CGPoint into nothing (an empty tuple). It’s referring to the return type, and if you look at the function signature for randomPointInRectangle you’ll notice that the return type is missing.

Solution

Don’t forget to include your return type in the function definition if you write return at the end of a function.

You can get some pretty strange and indirect error messages. Go back and fix the code to include the return type and the original logic.

func randomInt(number: Int) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomInt(number: CGFloat) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomPointInRectangle(rectangle: CGRect) -> CGPoint {
    return CGPoint(x: randomInt(rectangle.size.width), y: randomInt(rectangle.size.height))
} 

You have learned how to search for a solution to an error message, how to use DuckDuckGo.com when Google fails, and how to rewrite code to improve error messages in Swift.

Connect

Share the post if you found it helpful, or comment below.