Building Reusable Custom Components in UIKit with Swift
Most of the code I have written as a junior developer has been a variation of something I had already written. A row of icons, a pill-shaped button, a card with a title and a chevron — copy it into a new screen, nudge a few constraints, and hope the layout holds on a smaller phone. That hope rarely survives contact with a real user.
A reusable custom component removes the guesswork. It is a UIView subclass that owns its own layout, styling and behaviour, and accepts a small configuration object from the outside. You write it once, drop it into any screen, and change the theme in a single place when the design shifts. This is the pattern I reach for whenever an app starts to feel like a folder of screens instead of a product.
When a view deserves to become a component
The signal is duplication with a twist. The third copy of a layout usually arrives with a small difference from the first two — a longer title, an icon on the left instead of the right, a disabled state — and every one of those differences becomes a set of if statements inside two view controllers. When a designer asks for "the same button, but blue", and you find yourself editing five files, the view has outgrown its screen.
The other signal is change cost. If a new release can break the app because someone edited a hard-coded font size in one controller, the spacing rules for that component are scattered across the codebase. Pulling the view into a single class gives those rules one home.
Not everything needs abstraction, though. A view used on exactly one screen should stay private to that screen. The useful threshold is reuse or behavioural complexity: if the view has states, animations, accessibility behaviour or a configuration surface, it earns a class of its own. For a junior developer, this work is also where good habits form — naming, API design and clear responsibility are exactly the things reviewers look for in a portfolio project.
Designing the configuration API first
Before writing a single constraint, write the call site you wish you had. That future usage is your specification, and it tells you which inputs belong to the component and which stay outside it.
struct ActionButtonView {
struct Configuration {
var title: String
var style: Style = .filled
var icon: UIImage?
var isEnabled: Bool = true
var action: () -> Void
}
}
The configuration is a plain struct with default values, so a screen can override only what it cares about. Keeping the values immutable avoids surprises where a component mutates state the caller still owns.
A few rules keep this API honest. Mark the view class final unless you genuinely need subclassing, because overriding layout in a subclass is where Auto Layout conflicts usually begin. Use internal access by default and promote to public only when the component moves into a framework or package. Prefer a small enum over a growing list of booleans: isCompact and isFilled become isSmall and isLarge within a few sprints. And keep behaviour in the component, not in the configuration — the config should describe what the view shows, while the view decides how it responds.
Laying out the component with Auto Layout
Reusable views are usually built in code rather than in a storyboard. Code diffs read clearly in version control, there are no outlets to forget, and the same class can be instantiated in a unit test without loading a nib. Set translatesAutoresizingMaskIntoConstraints = false on the view and its subviews, then build the internal arrangement with UIStackView wherever the layout is a simple vertical or horizontal sequence.
final class ActionButtonView: UIView {
private let stack = UIStackView()
private let iconView = UIImageView()
private let titleLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
translatesAutoresizingMaskIntoConstraints = false
stack.axis = .horizontal
stack.spacing = 8
stack.alignment = .center
stack.addArrangedSubview(iconView)
stack.addArrangedSubview(titleLabel)
addSubview(stack)
}
}
For components with a natural size, return an intrinsicContentSize and let the stack's hugging and compression priorities do the rest. Avoid rebuilding constraints inside layoutSubviews on every pass; cache the constraints, or update them only when the configuration changes. Reserve draw(_:) for genuinely custom artwork such as dashed borders and badges, and let Auto Layout handle positioning.
A card component — image, title, supporting text, one button — describes half the screens in any app. Property listings, news tiles and the promotional panels on pages like live casino blackjack all stack the same three-part arrangement and then have to survive every screen width, from the small iPhone to the largest Pro Max model.
Supporting dark mode, dynamic type and localisation
Colour belongs in the asset catalog, with light and dark appearances defined there, so the component picks up a theme change without extra code. Use system semantic colours for backgrounds and labels so the view follows the user's settings, and reserve literal colours for brand elements only. On older deployment targets, traitCollectionDidChange(_:) gives you a hook to refresh anything that cannot be expressed in the catalog.
Dynamic Type needs deliberate handling. Set adjustsFontForContentSizeCategory = true on labels, size text with UIFont.preferredFont(forTextStyle: .body), and read the current UIContentSizeCategory when you need to measure. If the component has a fixed height, ask for a fitting size with systemLayoutSizeFitting instead of assuming a single point value. Australian users check balances in the ANZ or CBA app, order through the Woolworths or Coles apps and book flights on Qantas, and a large share of them run the system at increased text sizes, so a button that truncates at the accessibility sizes is a real bug.
Copy is part of the component's configuration too. Pass strings in rather than baking them into the class, format numbers and dates for Australian conventions such as dd/MM/yyyy, and remember that Australian English writes "colour", "favourite" and "organise" — wording differences show up in screenshots reviewed by local teams.
Making the component accessible and tappable
If the component responds to a tap, give it the affordances of a control. Subclassing UIControl means the view inherits keyboard focus, pointer interaction and assistive technology support, and you can wire actions with addTarget or the newer UIAction closure. Expose isEnabled and isSelected, and give the view a clear pressed state rather than relying on a colour shift alone.
VoiceOver needs explicit labels. Set isAccessibilityElement = true on the container, provide an accessibilityLabel that names the action, add accessibilityTraits such as .button or .header, and group child elements when they should be read as one phrase. Keep the hit area at least 44 by 44 points even if the visible shape is smaller, and check the result with the Accessibility Inspector on a real device rather than trusting the simulator.
The expectations are not unique to Apple platforms. Australian public-sector services are required to meet WCAG 2.2 AA, and that benchmark travels straight into the commercial apps Australians open every morning — the Optus and Telstra account apps, the Myer and JB Hi-Fi storefronts, the Afterpay checkout in a shopping app. Accessibility work is faster when it happens inside the reusable component, because fixing the label once fixes it on every screen that uses the view.
Packaging the component for reuse across projects
Inside one app, a folder such as Components/ActionButtonView with the source file and its tests is usually enough. The moment a widget, an extension or a second target needs the view, move it into a local Swift package: declare the supported platform, expose only what callers need, and keep the package versioned with semantic versioning so a breaking change is visible in the release tag.
For larger products, a framework target with its own resources — asset catalogs, strings, images — is the usual step, and the component then ships through your internal package registry rather than as loose files. That matters in Australian teams where the same product is maintained from offices in Sydney and Melbourne, with fintech work in Brisbane and resource platforms in Perth. Atlassian-style internal platforms and Canva-style design tooling both depend on components that travel between teams and repositories without drifting.
While packaging, resist the urge to generalise for hypothetical users. A component that handles one product's layouts usually serves that product better than a "universal" one with options for every case you can imagine.
Testing the component and shipping it with confidence
Xcode Previews are the fastest feedback loop for a reusable view. Use them to render the configurations you care about — default, disabled, long title — across light and dark appearances and several text size categories, so a layout regression shows up before it reaches a device. For components with a story, a small UIViewControllerRepresentable wrapper is enough to preview the UIKit view inside a SwiftUI preview.
Automated coverage should cover behaviour and appearance. Unit tests can assert that the configuration produces the expected title, enabled state and intrinsic size, while snapshot tests catch the visual changes that unit tests miss. UI tests then confirm the action fires and that the accessibility label is exposed correctly. Run the suite on GitHub Actions against a macOS runner so a broken constraint never reaches your teammates, and keep the component's test file next to the component rather than in a distant test target.
The practical takeaway is simple: find the view you copied most recently, give it one job, one configuration struct and one preview, and put it into the project this week. The second extraction will be easier than the first, and by the third your codebase reads like a product instead of a pile of screens — which is exactly the kind of work worth showing in a portfolio.