Just a bit recommendation about creating customized view programmatically and the reality about why type constructing with assortment views sucks.
How NOT to construct kinds for iOS apps?
Let’s begin with an sincere assertion: I tousled with this tutorial (quite a bit):
Building input forms for iOS apps
The factor is that this manner constructing methodology solely works if the cells are all the time seen on display screen, which is kind of a uncommon case. I found this challenge whereas I used to be engaged on my present challenge and a few fields had been continually disappearing and shifting the cursor to the subsequent enter subject stopped working when the cell was out of body.
Reusability & reminiscence effectivity just isn’t all the time what you need.
UICollectionView just isn’t the very best resolution for making enter kinds, as a result of the fixed cell reusability will mess up a number of the anticipated habits. It is nonetheless good for lists with “a thousand parts”, however for an enter type I’d not suggest this system anymore. Yep, my mistake, sorry about it… 😬
Studying by making errors
Lengthy story quick, I made a mistake and doubtless you may additionally make quite a bit throughout your developer profession. Does this make you a foul programmer? By no means. We’re human, we’re continually making smaller or greater errors, however…
(Stay and) flip it into energy
Your errors will all the time stick with you, however you’ll be able to be taught from them quite a bit. The issue solely begins in case you maintain doing the identical errors many times, or you do not even notice that you simply’re doing one thing flawed. It is actually arduous to take one step again and see the issue from a much bigger perspective. Typically you merely want another person to level out the problem for you, however adverse suggestions will also be painful.
Anyway, I do not wish to be an excessive amount of philosophical, it is a Swift developer weblog ffs.
A couple of issues that I discovered:
- my concepts are usually not all the time working, so do not belief me 100% (haha) 🤣
- it is all the time higher to code/work in pair with another person
- typically the “padawan” will educate the “grasp” 😉
- knowledgeable qa crew can prevent numerous time
- VIPER is my architectural “silver bullet”, not collection views
- UICollectionView based mostly 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 essentially the most fascinating 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 couple 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 wish to take care of these two init methods anymore, since I am utilizing auto structure and I am fully attempting to disregard interface builder with the tousled storyboards and nibs as properly.
class View: UIView @accessible(*, unavailable) override init(body: CGRect) tremendous.init(body: body) self.initialize() @accessible(*, 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 capabilities as unavailable, so noone can use them anymore. The one supply of fact shall be your individual init technique, which is kind of a aid in case you had been so irritated in regards to the tousled initialization course of like I used to be. 😤
Now you have got your individual base class that you should utilize as a dad or mum in your future views. In fact you may have to do the identical factor for nearly each UI ingredient, like labels, buttons, textfields, and so forth. That is numerous work, however on a long run it’s very price 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), ]
apply will be to have subclass for every customized consumer interface part, like the first button, secondary button, title label, header label, and so forth. This fashion you do not have to configure your views within the view controller, plus you’ll be able to put your ceaselessly used constraints into the subclass utilizing some helper strategies.
Additionally you’ll be able to have some niceextensions, these will help you with view configurations. You realize, identical to modifiers in SwiftUI. You’ll be able to even recreate the very same syntax. The underlying habits will not be the identical, however that is one other story. 📚
What in regards to the type new builder in iOS?
Oh, yeah virtually forgot. I’ve a model new, however nonetheless very comparable resolution. I am utilizing view subclasses as a substitute of assortment view parts, plus the gathering view have been changed with a
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 electronic mail = EmailTextField(id: "email-input", placeholder: "Electronic mail") self.stackView.addArrangedSubview(electronic 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 electronic 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: (electronic mail) - (password)")
As you’ll be able to see I am nonetheless utilizing the identical view identification technique, plus I nonetheless choose to have the SwiftUI-like
.onTouch motion handlers. You may ask although:
Why do not you merely go along with SwiftUI?
Properly, the factor is that SwiftUI is iOS13 solely, which is barely round ~55% adoption these days, that is one of many essential causes, but in addition SwiftUI is type 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 superb, however nonetheless it is a large leap ahead. Typically I consider that Apple is dashing issues simply due to advertising / 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 thought as a primary step… who is aware of… CoreKit -> AppleKit? 🤔
Anyway, you’ll be able to obtain a working instance of my newest type constructing resolution 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 e-newsletter beneath.
Leave a Reply