Customized views, enter varieties and errors

0/5 No votes

Report this app



Just a bit recommendation about creating customized view programmatically and the reality about why type constructing with assortment views sucks.


How NOT to construct varieties for iOS apps?

Let’s begin with an sincere assertion: I tousled with this tutorial (loads):

Constructing enter varieties for iOS apps

The factor is that this kind constructing methodology solely works if the cells are at all times seen on display screen, which is kind of a uncommon case. I found this concern whereas I used to be engaged on my present mission and a few fields had been continually disappearing and shifting the cursor to the following enter area stopped working when the cell was out of body.

Reusability & reminiscence effectivity just isn’t at all times what you need.

Looks like UICollectionView just isn’t the very best answer for making enter varieties, as a result of the fixed cell reusability will mess up a number of the anticipated conduct. It is nonetheless good for lists with “a thousand components”, however for an enter type I’d not advocate this method anymore. Yep, my mistake, sorry about it… ๐Ÿ˜ฌ

Studying by making errors

Lengthy story quick, I made a mistake and possibly you will additionally make loads throughout your developer profession. Does this make you a nasty programmer? In no way. We’re human, we’re continually making smaller or larger errors, however…

(Stay and) flip it into energy

Your errors will at all times stick with you, however you may study from them loads. The issue solely begins in case you hold doing the identical errors repeatedly, or you do not even understand that you just’re doing one thing unsuitable. It is actually onerous to take one step again and see the issue from an even bigger perspective. Generally you merely want another person to level out the problem for you, however unfavourable suggestions can be painful.

Anyway, I do not need to be an excessive amount of philosophical, it is a Swift developer weblog ffs.

A number of issues that I discovered:

  • my concepts should not at all times working, so do not belief me 100% (haha) ๐Ÿคฃ
  • it is at all times higher to code/work in pair with another person
  • typically the “padawan” will educate the “grasp” ๐Ÿ˜‰
  • knowledgeable qa group can prevent plenty of time
  • VIPER is my architectural “silver bullet”, not assortment views
  • UICollectionView primarily based type constructing just isn’t working…
  • …however the assortment view framework nonetheless rocks for complicated interfaces
  • have some devoted time for code cosmetics & refactor
  • use view subclasses programmatically (or SwiftUI sooner or later)

So the final level is probably the most attention-grabbing one, let me clarify why.

Customized view subclasses from code solely

Making a UIView subclass programmatically is a comparatively straightforward process. You’ll be able to load a nib file or you are able to do it straight from code. A number of weeks in the past I’ve discovered a brand new trick, that was bugging me on a regular basis I made a brand new subclass in Swift:

Why the hell do I’ve to implement init(coder:) if I am not utilizing IB in any respect?

Additionally what the heck is occurring with init(body:), I do not need to cope with these two init strategies anymore, since I am utilizing auto format and I am utterly attempting to disregard interface builder with the tousled storyboards and nibs as effectively.

class View: UIView {

    @obtainable(*, unavailable)
    override init(body: CGRect) {
        tremendous.init(body: body)


    @obtainable(*, unavailable)
    required init?(coder aDecoder: NSCoder) {
        tremendous.init(coder: aDecoder)


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


    func initialize() {
        self.translatesAutoresizingMaskIntoConstraints = false

The answer: mark these silly init features as unavailable, so noone can use them anymore. The one supply of reality shall be your personal init technique, which is kind of a reduction in case you had been so irritated concerning the tousled initialization course of like I used to be. ๐Ÿ˜ค

Now you might have your personal base class that you need to use as a father or mother in your future views. After all you will have to do the identical factor for nearly each UI factor, like labels, buttons, textfields, and many others. That is plenty of work, however on a long run it’s very price it.

import UIKit

class TitleLabel: Label {

    override func initialize() {

        self.textAlignment = .middle
        self.font = UIFont.preferredFont(forTextStyle: .largeTitle)
        self.textColor = .systemBlue

    func constraints(in view: UIView, padding: CGFloat = 8) -> [NSLayoutConstraint] {
            self.topAnchor.constraint(equalTo: view.topAnchor, constant: padding),
            self.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding),
            self.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -1 * padding),

A superb apply could be to have subclass for each customized person interface element, like the first button, secondary button, title label, header label, and many others. This manner you do not have to configure your views within the view controller, plus you may put your regularly used constraints into the subclass utilizing some helper strategies.

Additionally you may have some niceextensions, these may also help you with view configurations. You already know, identical to modifiers in SwiftUI. You’ll be able to even recreate the very same syntax. The underlying conduct will not be the identical, however that is one other story. ๐Ÿ“š

What concerning the type new builder in iOS?

Oh, yeah nearly forgot. I’ve a model new, however nonetheless very related answer. I am utilizing view subclasses as a substitute of assortment view elements, plus the gathering view have been changed with a UIScrollView + UIStackView mixture. ๐Ÿ

class ViewController: UIViewController {

    weak var scrollView: ScrollView!
    weak var stackView: VerticalStackView!

    override func loadView() {

        let scrollView = ScrollView()
        self.scrollView = scrollView

        let stackView = VerticalStackView()
        self.stackView = stackView

    override func viewDidLoad() {

        self.title = "StackForm"
        self.navigationController?.navigationBar.prefersLargeTitles = true

        let e mail = EmailTextField(id: "email-input", placeholder: "E-mail")
        self.stackView.addArrangedSubview(e mail)

        let password = PasswordTextField(id: "password-input", placeholder: "Password")

        let submit = SubmitButton(id: "submit-button", title: "Submit")
        .onTouch { [weak self] _ in self?.submit() }

    func submit() {
            let e mail = (self.view.view(withId: "email-input") as? UITextField)?.textual content,
            let password = (self.view.view(withId: "password-input") as? UITextField)?.textual content
        else {
        print("Account: (e mail) - (password)")

As you may see I am nonetheless utilizing the identical view identification approach, plus I nonetheless want to have the SwiftUI-like .onTouch motion handlers. You may ask although:

Why do not you merely go together with SwiftUI?

Effectively, the factor is that SwiftUI is iOS13 solely, which is just round ~55% adoption these days, that is one of many most important causes, but additionally SwiftUI is form of incomplete.

I am attempting to get as shut as I can to SwiftUI, so the transition shall be much less ache within the ass when the time comes. SwiftUI shall be wonderful, however nonetheless it is a large leap ahead. Generally I consider that Apple is speeding issues simply due to advertising / developer wants (yeah, we’re very impatient animals). Possibly a easy wrapper framework round UIKit / AppKit with out the entire declarative syntax would have been a greater thought as a primary step… who is aware of… CoreKit -> AppleKit? ๐Ÿค”

Anyway, you may obtain a working instance of my newest type constructing answer in Swift 5 from GitHub. Simply search for the StackForm folder contained in the repository.

Thanks for studying, I am attempting please assist me by following on twitter and remember to subscribe to my month-to-month publication under.


Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.