Saturday, May 14, 2016

Customizing Xcode with Designables

You ever find yourself subclassing a UI control to customize it or customizing the look of a UI control in your viewDidLoad? And then you have to keep running the simulator to see if your control looks right?

There is an easier way, my friends. Using @IBDesignables (Interface Builder Designables) you can update your UI control realtime in the Attributes Inspector when you are on your storyboard or xib and see your changes real-time.

I will use an example of adding rounded corners to my buttons.

1. Add a file to your project and paste in this code:
import UIKit

@IBDesignable class RoundedCornerButton: UIButton {

    override func drawRect(rect: CGRect) {
        self.clipsToBounds = true
    }
    
    @IBInspectable var cornerRadius: CGFloat = 0 {
        didSet {
            self.layer.cornerRadius = cornerRadius
        }
    }
}
2. Drop a button on to your xib or storyboard and give it a background color. Then go to the Identity Inspector and select RoundedCornerButton.

Take a close look here. Notice there is now a property called "Designables" and it says "Up to date".

3. Go to the Attributes Inspector and now you it shows new properties that can be set for your button:

This shows because you selected RoundedCornerButton in the Identity Inspector on the previous step.

4. Change the value for the Corner Radius. Your button is changing right in Interface Builder (on xib or storyboard)!
This allows you to better predict how your UI will look and save you time from having to constantly run your app to see how your controls render.

(Swift 2.2)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...