27 Jan, 2020

ViewModifiers are css except much better

ViewModifiers are css except much better

From time to time developing iOS project I would look at CSS with a kind of envy that I would not admit. I envied how easy it is to accomplish certain tasks, for example, being able to declare a style with :before and :after pseudo elements.

When you do that you can, for example, decorate titles with adornments that are placed on right and left of a title. Like this:

h1::after {
    content: " ::";

h1::before {
    content: ":: ";

Which would produce this result:

alt text

UIKit for all its belts and whistles was just not build to work like that. Creating such a reusable component would involve creating a UIView subclass and going trough the minor hassle of arranging UILabel subviews to the desired effect.

It also wouldn’t be the most straight forward to pull off if you take into account the Auto Layout configuration you would need if you wanted this title to expand to fit the text in it AND play nice with views around it.

That’s why I am pleasantly surprised once I started to get my head into SwiftUI’s ViewModifier feature which can easily be used to this effect.

import SwiftUI

@available(iOS 13, macCatalyst 13, tvOS 13, watchOS 6, *)
struct H1: ViewModifier {
    func body(content: Content) -> some View {
        HStack {
                .padding(EdgeInsets(top: 0.0, leading: 0.0, bottom: 0.0, trailing: 10.0))
                .padding(EdgeInsets(top: 0.0, leading: 10.0, bottom: 0.0, trailing: 0.0))

@available(iOS 13, macCatalyst 13, tvOS 13, watchOS 6, *)
extension Text {
    func h1() -> some View {
        return self.modifier(H1())

struct ContentView: View {
    var body: some View {
        Text("SUPER COOL TITLE").h1()

Isn’t that cool?

Made my day :)

PS : Now, saying that ViewModifiers are CSS is not totally accurate. They are so much more powerful! But this is what it made me think of.

Grab some code here: 90sBrowserNavigationBarTitle


My name is Juan Carlos Ospina Gonzalez and I am an experienced iOS Developer with a strong background in Art and Design.

My education in Graphic Design and New Media combined with over 15 years of experience in Software Development gives me a good overview and insight in the creation of Digital products.

As a technical leader I can communicate effectively with stake holders and break down wishes and ideas into well-grounded feature definitions. I can gather technical requirements and provide well informed feedback during design iterations.

During development I enjoy planning architecture, setting up infrastructure for continuous integration and writing sane code supported by testing and code-review practices to ensure high quality software is delivered to the final phases of QA.

I enjoy working in a team of my peers where an atmosphere of constant research, collaboration and mutual mentoring ensure continuous personal and professional growth.