Saturday, November 8, 2025
HomeiOS DevelopmentCustomized views, enter kinds and errors

Customized views, enter kinds and errors

[ad_1]

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

iOS

How NOT to construct kinds for iOS apps?

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

Constructing enter kinds for iOS apps

The factor is that this manner constructing methodology solely works if the cells are at all times seen on display screen, which is sort of a uncommon case. I found this challenge whereas I used to be engaged on my present challenge and a few fields have been always disappearing and shifting the cursor to the subsequent enter discipline stopped working when the cell was out of body.

Reusability & reminiscence effectivity is just not at all times what you need.

Looks like UICollectionView is just not the perfect resolution for making enter kinds, 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 kind I might not advocate this system anymore. Yep, my mistake, sorry about it… 😬


Studying by making errors

Lengthy story brief, I made a mistake and doubtless you will additionally make so much throughout your developer profession. Does this make you a nasty programmer? Under no circumstances. We’re human, we’re always making smaller or larger errors, however…

(Stay and) flip it into energy

Your errors will at all times stick with you, however you possibly can be taught from them so much. The issue solely begins in the event you hold doing the identical errors time and again, or you do not even understand that you simply’re doing one thing incorrect. It is actually onerous to take one step again and see the issue from an even bigger perspective. Typically you merely want another person to level out the difficulty for you, however unfavorable suggestions will also be painful.

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

Just a few issues that I discovered:

  • my concepts usually are 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 train the “grasp” 😉
  • knowledgeable qa group can prevent lots of time
  • VIPER is my architectural “silver bullet”, not assortment views
  • UICollectionView based mostly kind constructing is just not working…
  • …however the assortment view framework nonetheless rocks for advanced interfaces
  • have some devoted time for code cosmetics & refactor
  • use view subclasses programmatically (or SwiftUI sooner or later)

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


Customized view subclasses from code solely

Making a UIView subclass programmatically is a comparatively simple job. You possibly can load a nib file or you are able to do it straight from code. Just a few 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 wish to cope with these two init strategies anymore, since I am utilizing auto structure and I am utterly making an attempt to disregard interface builder with the tousled storyboards and nibs as properly.

class View: UIView {

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

        self.initialize()
    }

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

        self.initialize()
    }

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

        self.initialize()
    }

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

The answer: mark these silly init features as unavailable, so noone can use them anymore. The one supply of fact might be your individual init technique, which is sort of a reduction in the event you have been so irritated in regards to the tousled initialization course of like I used to be. 😤

Now you could have your individual base class that you need to use as a dad or mum on your future views. In fact you will have to do the identical factor for nearly each UI factor, like labels, buttons, textfields, and so forth. That is lots of work, however on a long run it’s very value it.

import UIKit

class TitleLabel: Label {

    override func initialize() {
        tremendous.initialize()

        self.textAlignment = .heart
        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 very good follow will be to have subclass for each customized person interface part, like the first button, secondary button, title label, header label, and so forth. This manner you do not have to configure your views within the view controller, plus you possibly can put your steadily used constraints into the subclass utilizing some helper strategies.

Additionally you possibly can have some niceextensions, these might help you with view configurations. You recognize, similar to modifiers in SwiftUI. You possibly can even recreate the very same syntax. The underlying conduct will not be the identical, however that is one other story. 📚


What in regards to the kind new builder in iOS?

Oh, yeah virtually forgot. I’ve a model new, however nonetheless very related resolution. I am utilizing view subclasses as a substitute of assortment view parts, 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() {
        tremendous.loadView()

        let scrollView = ScrollView()
        self.view.addSubview(scrollView)
        self.scrollView = scrollView
        NSLayoutConstraint.activate([/*...*/])

        let stackView = VerticalStackView()
        self.scrollView.addSubview(stackView)
        self.stackView = stackView
        NSLayoutConstraint.activate([/*...*/])
    }

    override func viewDidLoad() {
        tremendous.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")
        self.stackView.addArrangedSubview(password)

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

    func submit() {
        guard
            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 {
            return
        }
        print("Account: (e mail) - (password)")
    }
}

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

Why do not you merely go along with SwiftUI?

Nicely, the factor is that SwiftUI is iOS13 solely, which is barely round ~55% adoption these days, that is one of many predominant causes, but in addition SwiftUI is type of incomplete.

I am making an attempt to get as shut as I can to SwiftUI, so the transition might be much less ache within the ass when the time comes. SwiftUI might be superb, however nonetheless it is a big leap ahead. Typically I consider that Apple is dashing issues simply due to advertising and marketing / developer wants (yeah, we’re very impatient animals). Perhaps a easy wrapper framework round UIKit / AppKit with out the entire declarative syntax would have been a greater concept as a primary step… who is aware of… CoreKit -> AppleKit? 🤔

Anyway, you possibly can obtain a working instance of my newest kind constructing resolution in Swift 5 from GitHub. Simply search for the StackForm folder contained in the repository.

Thanks for studying, I am making an attempt please assist me by following on twitter and remember to subscribe to my month-to-month publication beneath.




[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments