Saturday, November 7, 2026
HomeiOS DevelopmentStyling by subclassing - The.Swift.Dev.

Styling by subclassing – The.Swift.Dev.

[ad_1]

Learn to design and construct reusable consumer interface parts through the use of customized view subclasses from the UIKit framework in Swift.

UIKit

The issue: UI, UX, design

Constructing consumer interfaces is the toughest a part of the job!

In a nutshell: design is a strategy of determining the perfect resolution that matches a selected downside. Graphic design normally means the bodily drawing on a canvas or a paper. UX is actually how the consumer interacts with the applying, in different phrases: the general digital expertise of the “buyer” journey. UI is the seen interface that he/she is going to see and work together with by touching the display. 👆

If I’ve to placed on the designer hat (and even the developer hat) I’ve to inform you that determining and implementing correct consumer interfaces is probably the most difficult downside in a lot of the instances. Frontend methods these days (cell, pill, even desktop apps) are simply fancy overlays on high of some JSON knowledge from a service / API. 🤷‍♂️

Why is it so arduous? Effectively, I imagine that if you wish to be a superb designer, you want a correct engineering mindset as effectively. It’s a must to be able to observing the complete system (large image), assemble constant UI parts (that really look the identical all over the place), plan the desired expertise primarily based on the purposeful specification and plenty of extra. It is also fairly a primary requirement to be an artist, suppose outdoors of the field, and be capable of clarify (describe) your thought to others. 🤯

Now inform me whose job is the toughest within the tech business? Yep, as a free of charge everyone seems to be a designer these days, additionally some firms do not rent this sort of specialists in any respect, however merely let the work performed by the builders. Anyway, let’s give attention to learn how to create good and reusable design implementations through the use of subclasses in Swift. 👍


Look, themes and kinds

Let me begin with a confession: I barely use the UIAppearance API. It is a private desire, however I prefer to set design properties like font, textColor, backgroundColor straight on the view situations. Though in some instances I discovered the looks proxy very good, however nonetheless slightly buggy. Perhaps it will change with iOS 13 and the arrival of the lengthy awaited darkish mode.

Expensive Apple please make an auto swap primarily based on day / evening cycles (you realize just like the sundown, dawn possibility within the house app). 🌙

  • Model is a set of attributes that specifiy the looks for a single view.
  • Theme is a set of comparable trying view kinds, utilized to the entire utility.

These days I normally create some predefined set of styling parts, almost certainly fonts, colours, however generally icons, and many others. I prefer to go together with the next construction:

Fonts

  • title
  • heading
  • subheading
  • physique
  • small

Colours

Icons

You may have much more parts, however for the sake of simplicity let’s simply implement these ones with a very easy Swift resolution utilizing nested structs:

struct App {

    struct Fonts {
        static let title = UIFont.systemFont(ofSize: 32)
        static let heading = UIFont.systemFont(ofSize: 24)
        static let subheading = UIFont.systemFont(ofSize: 20)
        static let physique = UIFont.systemFont(ofSize: 16)
        static let small = UIFont.systemFont(ofSize: 14)
    }

    struct Colours {
        static let title = UIColor.blue
        static let heading = UIColor.black
        static let background = UIColor.white
    }

    struct Icons {
        static let again = UIImage(named: "BackIcon")!
        static let share = UIImage(named: "ShareIcon")!
    }

}


App.Fonts.title
App.Colours.background
App.Icons.again

This fashion I get a reasonably easy syntax, which is sweet, altough this would possibly not let me do dynamic styling, so I cannot swap between gentle / darkish theme, however I actually do not thoughts that, as a result of in a lot of the instances it is not a requirement. 😅

Structs vs enums:

I might use enums as a substitute of structs with static properties, however on this case I just like the simplicity of this method. I do not need to fiddle with uncooked values or extensions that accepts enums. It is only a private desire.

What if you need to assist a number of themes?

That is not a giant challenge, you may outline a protocol on your wants, and implement the required theme protocol as you need. The true downside is when you need to swap between your themes, as a result of you need to refresh / reload your total UI. ♻️

There are some greatest practices, for instance you need to use the NSNotificationCenter class with a view to notify each view / controller in your app to refresh if a theme change happens. One other resolution is to easily reinitialize the entire UI of the applying, so this implies you principally begin from scratch with a model new rootViewController. 😱

Anyway, examine the hyperlinks beneath if you happen to want one thing like this, however if you happen to simply need to assist darkish mode in your app, I might counsel to attend till the primary iOS 13 beta comes out. Perhaps Apple will give some shiny new API to make issues simple.


Customized views as fashion parts

I promised styling by subclassing, so let’s dive into the subject. Now that we’ve a superb resolution to outline fonts, colours and different primary constructing blocks, it is time to apply these kinds to precise UI parts. After all you need to use the UIAppearance API, however for instance you may’t merely set customized fonts via the looks proxy. 😢

One other factor is that I like consistency in design. So if a title is a blue, 32pt daring system font someplace in my utility I additionally count on that factor to observe the identical guideline all over the place else. I resolve this downside by creating subclasses for each single view factor that has a customized fashion utilized to it. So for instance:

  • TitleLabel (blue colour, 32pt system font)
  • HeadingLabel (blue colour, 24pt system font)
  • StandardButton (blue background)
  • DestructiveButton (crimson background)

One other good factor when you have subclasses and also you’re working with autolayout constraints from code, you could put all of your constraint creation logic straight into the subclass itself. Let me present you an instance:

import UIKit

class TitleLabel: UILabel {

    override init(body: CGRect) {
        tremendous.init(body: body)

        self.initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        tremendous.init(coder: aDecoder)

        self.initialize()
    }

    init() {
        tremendous.init(body: .zero)

        self.initialize()
    }

    func initialize() {
        self.translatesAutoresizingMaskIntoConstraints = false
        self.textColor = App.Colours.title
        self.font = App.Fonts.title
    }

    func constraints(in view: UIView) -> [NSLayoutConstraint] {
        return [
            self.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16),
            self.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16),
            self.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        ]
    }
}

As you may see I solely must set the font & textColor attributes as soon as, so after the view initialization is completed, I can make certain that each single occasion of TitleLabel will look precisely the identical. The utilization is fairly easy too, you simply must set the category identify in interface builder, or you may merely create the view like this:


let titleLabel = TitleLabel()
self.view.addSubview(titleLabel)
NSLayoutConstraint.activate(titleLabel.constraints(in: self.view))

The factor I like probably the most about this method is that my constraints are going to be simply in the best place, so they will not bloat my view controller’s loadView technique. You may also create a number of constraint variations primarily based in your present scenario with further parameters, so it is fairly scalable for each scenario. 👍

View initialization is tough

The draw back of this resolution is that view initialization is sort of tousled, due to the interface builder assist. It’s a must to subclass each single view kind (button, label, and many others) and actually copy & paste your initialization strategies time and again. I have already got some articles about this, examine the hyperlinks beneath. 👇

With the intention to resolve this downside I normally find yourself by making a mum or dad class for my very own styled views. Right here is an instance for an summary base class for my labels:

class Label: UILabel {

    override init(body: CGRect) {
        tremendous.init(body: body)

        self.initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        tremendous.init(coder: aDecoder)

        self.initialize()
    }

    init() {
        tremendous.init(body: .zero)

        self.initialize()
    }

    func initialize() {
        self.translatesAutoresizingMaskIntoConstraints = false
    }
}

So any more I simply must override the initialize technique.

class TitleLabel: Label {

    override func initialize() {
        tremendous.initialize()

        self.font = App.Fonts.title
        self.textColor = App.Colours.title
    }
}

See, it is so a lot better, as a result of I haven’t got to take care of the required view initialization strategies anymore, additionally autoresizing shall be off by default. ❤️

My remaining takeaway from this lesson is that you simply shouldn’t be afraid of lessons and object oriented programming if it involves the UIKit framework. Protocol oriented programming (additionally purposeful programming) is nice if you happen to use it in the best place, however since UIKit is sort of an OOP framework I imagine it is nonetheless higher to observe these paradigms as a substitute of selecting some hacky means. 🤪

In the event you like my publish, please additionally observe me on twitter, and subscribe to my month-to-month e-newsletter. It is 100% Swift solely content material, no spam ever!



[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments