Write less UI code

Related tags

Layout Layoutless
Overview

Carthage compatible Platform Twitter

Layoutless

Layoutless enables you to spend less time writing UI code. It provides a way to declaratively style and layout views. Here is an example of how UI code looks like when written against Layoutless:

class ProfileView: View {

    let imageView = UIImageView(style: Stylesheet.profileImage)
    let nameLabel = UILabel(style: Stylesheet.profileName)

    override var subviewsLayout: AnyLayout {
        return stack(.vertical, alignment: .center)(
            imageView,
            nameLabel
        ).fillingParent(insets: 12)
    }
}

Layoutless is not just another DSL that simplifies Auto Layout code, rather it is a layer on top of Auto Layout and UIKit that provides a way to abstract common layout patterns and enable consistent styling approach. It is a very lightweight library - around 1k lines of code.

There are three main features of Layoutless.

Layout Patterns

In order to make UI code more declarative, one has to have a way of abstracting and reusing common layout patterns like the sizing of views, laying a view out in a parent or stacking and grouping multiple views together. Layoutless makes this possible by providing types that enable you to make such patterns.

Basic Patterns

Walkthrough

Imagine that we need to build a news article screen where we have an image on top and a text below it representing the article body. First, we would define our views like:

let imageView = UIImageView()
let bodyLabel = UILabel()

Let us now build our layout. A layout is something that defines how individual views are sized, positioned and structured withing a view hierarchy. Layoutless can represent layout with the Layout type, however, we rarely have to work with it directly because the framework provides extensions methods on UIView and few global functions that can be used to build layouts.

For example, to stack our two views vertically, we can use stack function:

let layout = stack(.vertical)(
    imageView,
    bodyLabel
)

Next, we would prefer if the body would have some side margins, so it is not laid out from the edge to the edge of the screen. That is as simple as insetting a view:

let layout = stack(.vertical)(
    imageView,
    bodyLabel.insetting(left: 18, right: 18)
)

All fine, until we hit a news article that does not fit on the screen. Oh boy, not scroll views... Well, with Layoutless they are a joy. To make our stack scrollable, all we have to do is chain one more method call:

let layout = stack(.vertical)(
    imageView,
    bodyLabel.insetting(left: 18, right: 18)
).scrolling(.vertical)

Now our stack is vertically scrollable. Finally, we need to define how our scrollable stack is laid out within the parent. We want to fill the parent, i.e. constrain all four edges to the parent's edges. We can do this:

let layout = stack(.vertical)(
    imageView,
    bodyLabel.insetting(left: 18, right: 18)
).scrolling(.vertical).fillingParent()

What we end up with is a layout variable that is an instance of the Layout type. It represents a description of our layout. Nothing has actually been laid out at this point yet. No constraints have been set up yet. To build the layout and make the framework create all relevant constraints and intermediary views, we need to lay our layout out:

layout.layout(in: parentView)

And that's it! The framework will create necessary Auto Layout constraints, embed the stack into a scroll view and add that as a subview of our parent view. To learn more about additional layout patterns, peek into the implementation. It's crazy simple! You can easily create your own patterns. If you think you have something that could be useful for everyone, feel free to make a PR.

Keep reading if you wish things were even simpler.

Base Views

Building declarative layouts is an awesome experience, but that last line to lay our layout out is not really declarative, it is an imperative call and we are not happy about it.

What we need is a place where we can just put our layout and let the "system" decide when it needs to be laid out. For that reason, Layoutless provides subclasses of base UIKit views that we should use as building blocks for our layouts. Those subclasses are very trivial, but they enable us to do this:

class ArticleView: View { // or ArticleViewController: ViewController

    let imageView = UIImageView()
    let bodyLabel = UILabel()

    override var subviewsLayout: AnyLayout {
        return stack(.vertical)(
            imageView,
            bodyLabel.insetting(left: 18, right: 18)
        ).scrolling(.vertical).fillingParent()
    }
}

View is basically a UIView subclass with subviewsLayout property that we can override to provide our own layout. That is all there is to it. Check it out.

Layoutless provides base views like: View, Control, Label, Button, ImageView, TextField, etc.

Styling

For UI code to be more declarative, apart from solving the layout problem, we also have to solve the styling problem. It turns out, there is a very simple solution to that problem. You can find a detailed explanation of the solution presented in the article about it, so let's just see how it works.

We will define something called Stylesheet in an extension of the view or the view controller we are about to style. A Stylesheet is just a namespace (i.e. an enum) with a collection of styles.

extension ArticleView {

    enum Stylesheet {

        static let image = Style<UIImageView> {
            $0.contentMode = .center
            $0.backgroundColor = .lightGray
        }

        static let body = Style<UILabel> {
            $0.font = .systemFont(ofSize: 14)
            $0.textColor = .black
        }
    }
}

As you can see, each style is an instance of Style type. You create Style by providing a closure that styles a view of a given type. That's all there is to it.

To use our styles, we will just instantiate our views using the convenience initializers provided by the framework:

class ArticleView: View {

    let imageView = UIImageView(style: Stylesheet.image)
    let bodyLabel = UILabel(style: Stylesheet.body)

    ...
}

😍

Advanced

Layout Sets

Universal apps usually provide different layouts based on the screen size. An app that supports both iPhone orientations and an iPad could provide for example three different layouts for some or all of its screens. An iPad app will usually provide one layout in fullscreen mode and another in split screen mode. Most of these scenarios require screens to dynamically update layout as the user interacts with the app or device (for example rotates it). In real life that means maintaining different sets of constraints and activating or deactivating them as needed.

Layoutless makes all that easy. All you need to do is define different layouts based on the set of traits and let the framework handle everything else, from choosing the appropriate layout to dynamically changing the layout when the set of traits changes. Just define layouts as you normally would and then use layoutSet to build the final layout (or just part of the layout) that is conditional based on the trait currently active. For example, to provide one layout for portrait and other for landscape one could do:

class MyViewController: ViewController {

    override var subviewsLayout: AnyLayout {

        let portrait: AnyLayout = ...
        let landscape: AnyLayout = ...

        return layoutSet(
            traitQuery(traitCollection: UITraitCollection(horizontalSizeClass: .compact)) { portrait },
            traitQuery(traitCollection: UITraitCollection(horizontalSizeClass: .regular)) { landscape }
        )
    }
}

As we can see, within layoutSet we list a number of queries. Each query represents a layout that is going to be active when the trait query matches current traits. We can query by UITraitCollection or by screen size. For example:

layoutSet(
    traitQuery(width: .lessThanOrEqual(1000)) { ... },
    traitQuery(width: .greaterThanOrEqual(1000)) { ... }
)

Query trait sets should be disjunct sets.

Note that app's key window must be Layoutless Window or its subclass for the dynamic layout change to work.

Requirements

  • iOS 9.0+ / tvOS 9.0+
  • Xcode 9

Installation

Carthage

github "DeclarativeHub/Layoutless"

CocoaPods

pod 'Layoutless'

Communication

  • If you would like to ask a general question, open a question issue.
  • If you have found a bug, open an issue or do a pull request with the fix.
  • If you have a feature request, open an issue with the proposal.
  • If you want to contribute, submit a pull request (include unit tests).

License

The MIT License (MIT)

Copyright (c) 2017-2018 Srdan Rasic (@srdanrasic)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • Compilation issues after upgrading to Xcode 10.2

    Compilation issues after upgrading to Xcode 10.2

    Problem description

    Been using Layoutless in my Views before upgrading to 10.2 with no issues. However after upgrading to 10.2, I get the following compilation errors :

    Cannot find interface declaration for 'ViewController', superclass of 'RegistrationViewController'; did you mean 'UIViewController'?
    
    Cannot find interface declaration for 'ViewController', superclass of 'SchedulesController'; did you mean 'UIViewController'?
    ...
    

    Those issues all appear in the Binder section of my code where I am defining extensions as per the Binder Architecture.

    So, for example, in my View module, the RegistrationViewController defines :

    public class RegistrationViewController: ViewController { ... }

    and in the Binder module :

    extension RegistrationViewController { ... }

    I tried rebuilding each module separately (after clearing out the build cache), but to no avail.

    Any ideas ?

    opened by npvisual 12
  • Manual autolayout block and hierarchies

    Manual autolayout block and hierarchies

    Hey, nice work! The only thing I found a bit hard is lacking of documentation and examples.

    I have 3 questions:

    1. A question regarding using autolayout manually with Layoutless. For instance I have a stack layout which and I want to show a view on a bottom right, or do some more sophisticated stuff.
    return group(
        stack(.vertical)(
            firstLabel,
            secondLabel
            ).sizing(toWidth: 280).centeringInParent(relativeToSafeArea: true).layoutRelativeToDescendent(view) { ... }
    }
    

    I've tried a bunch of ways to do it and I usually get an exception that views are in different hierarchies.

    1. And what if I want to manage view both with layoutless and with manual autolayout block? Like
    return group(
        stack(.vertical)(
            firstLabel,
            secondLabel
            ).sizing(toWidth: 280).centeringInParent(relativeToSafeArea: true),
        view.centeringHorizontallyInParent.layoutRelativeToDescendent(/* what should I put here? */)
    }
    
    1. How do you manage adding views to another views using Layoutless? So if I have
        public var imageView = ImageView(myImage)
    

    Can I add a view to imageView and manage it's layout with Layoutless without subclassing ImageView?

    opened by pankkor 3
  • Retain cycle at TraitQueryLayoutSet

    Retain cycle at TraitQueryLayoutSet

    I've noticed then whenever I'm using TraitQueryLayoutSet by calling layoutSet(...), my subviews stay in memory even when the view controller itself is closed and destroyed. In my case, it was an instances of MKMapView which are quite heavy so it was easy to spot.

    Screenshot 2020-11-29 at 23 15 54

    I've tried to fix it and memory leaks are gone. But since I don't want to break anything, I've spent some time figuring out how Layoutless works and what might cause the problem. So here is what I've got:

    1. TraitQueryLayoutSet has a property called parentRevertable that is used to store other Revertables. So far it looks to me that Revertable is used for deactivating constraints and removing subviews from the hierarchy. Sort of "reverting" applied changes.
    2. Revertable which is created when we call TraitQueryLayoutSet.layout(in container: UIView) has an implicit strong capture of self what creates a retain cycle that looks like TraitQueryLayoutSetRevertableClosureTraitQueryLayoutSet. Unfortunately, I wasn't able to capture it using XCode memory graph so I don't have a proof that that's exactly how it works.
    3. To break this cycle, I've replaced this capture with a weak one. The obvious side-effect of this is that when the closure will be performed, the self might be nil and some changes won't be applied.
    4. But if I'm right, this is totally fine because we call TraitQueryLayoutSet.layout(in container: UIView), layout set adds itself into the passed container using ___associatedObjects using a strong link, because the used policy is OBJC_ASSOCIATION_RETAIN_NONATOMIC. So while our container is alive, TraitQueryLayoutSet will be alive too since we have a strong link. And when your container is destroyed, there is no need to keep TraitQueryLayoutSet since it's responsible only for layout updates.

    So if I'm got this right, my pull request should fix the problem just fine. Otherwise, please, correct me on any of the above.

    opened by someyura 1
  • Problems with Swift 5.1 and Xcode 11.0 beta 4

    Problems with Swift 5.1 and Xcode 11.0 beta 4

    Installing Layoutless via Carthage using Xcode 11.0 beta 4 and Swift 5.1 results in the following error:

    Build Failed
    	Task failed with exit code 65:
    	/usr/bin/xcrun xcodebuild -workspace /path/to/app/Carthage/Checkouts/Layoutless/Layoutless.xcworkspace -scheme Layoutless-iOS -configuration Release -derivedDataPath /Users/mario/Library/Caches/org.carthage.CarthageKit/DerivedData/11.0_11M374r/Layoutless/0.4.1 -sdk iphoneos ONLY_ACTIVE_ARCH=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES archive -archivePath /var/folders/b_/n__v03ld5614t94z1y10nfqm0000gn/T/Layoutless SKIP_INSTALL=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=NO CLANG_ENABLE_CODE_COVERAGE=NO STRIP_INSTALLED_PRODUCT=NO (launched in /path/to/app/Carthage/Checkouts/Layoutless)
    

    The log contains this lines at the bottom:

    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    
    ** ARCHIVE FAILED **
    
    
    The following build commands failed:
    	Ld /Users/mario/Library/Caches/org.carthage.CarthageKit/DerivedData/11.0_11M374r/Layoutless/0.4.1/Build/Intermediates.noindex/ArchiveIntermediates/Layoutless-iOS/IntermediateBuildFilesPath/Layoutless.build/Release-iphoneos/Layoutless-iOS.build/Objects-normal/arm64/Binary/Layoutless normal arm64
    (1 failure)
    
    opened by ream88 1
  • Added configure to stack in order to pull out UIStackView for later use

    Added configure to stack in order to pull out UIStackView for later use

    I copied the configure from the scrollview in order to pull out stackviews for later us. Sometimes I'd like to retain a reference to the stackview for later addition of elements.

    opened by theisegeberg 1
  • Styling API improvements

    Styling API improvements

    I can update & integrate a builder for styling if you find it interesting, so users will be able to avoid $0... stuff Example (needs to be updated to fully support get-only reference configuration) can be found on gist For now, I think it's the best API for styling the UI. Also, I find your layout system very attractive, just to mention ❤️

    Tagging @rebeloper, because that may also be useful for his SparkUI framework 🙂

    A few days ago I found something similar to my builder https://github.com/marty-suzuki/DuctTape, but there are a few things to improve btw in both of implementations.

    opened by maximkrouk 1
  • Layoutless demo with all use cases of the SDK

    Layoutless demo with all use cases of the SDK

    Hi, Great framework that makes developer lives easier in terms of building the UI components which consumes a lot of time by using auto layout engine. This SDK provides the full abstraction over auto layout, but unfortunately i am unable to find the complete potential of the framework in terms of show casing the demo examples. Please provide a demo with more use cases of the framework.

    Thanks & Cheers, Pradeep Kumar.M

    opened by pradweep 0
  • FREE YouTube VIDEO TUTORIAL

    FREE YouTube VIDEO TUTORIAL

    Hi, Love Layoutless. So I made a 25 minutes long YouTube tutorial explaining it: https://youtu.be/DhXUo9PrWYg

    Feel free to add it to the README / Documentation / Cheat Sheet with this image [people tap on images more than on boring links :) ] autolayout-ios-programmatically-spend-less time-writing-UI-code Hope you like it. I'm open to any feedback.

    opened by rebeloper 0
  • Scroll to top

    Scroll to top

    Hi, I have some views stacked out in an UIView. This stack has the .scrolling(.vertical) modifier.

    let scrollingContainerView = UIView()
    
    ...
    
    stack(.vertical)(
                topContainerView.insetting(by: UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12)),
                middleContainerView.insetting(by: 12),
                bottomContainerView.insetting(by: UIEdgeInsets(top: 12, left: 0, bottom: 12, right: 0))
                ).scrolling(.vertical).fillingParent().layout(in: scrollingContainerView)
    

    Is there a way to scroll the scrollingContainerView to top?

    Thank you.

    opened by rebeloper 0
  • How to reload the layout

    How to reload the layout

    Hi,

    Not sure if this has been handled or not, but I couldn't find a way to reload the base view/stack view. Is the support added, if yes, could you please help me with that?

    Also, I need a way to modify a height of a view based on some condition. For eg., in landscape I need the view to take 100 px height and in portrait it should take 150 px. Is there any way we can achieve that?

    opened by varunpm1 0
Releases(0.4.3)
Owner
Declarative Hub
Declarative Hub
iOS constraint maker you always wanted. Write constraints like sentences in English. Simple

YeahLayout iOS constraint maker you always wanted. Write constraints like sentences in English. Simple. Intuitive. No frightening abstractions. One fi

Андрей Соловьев 1 Jan 10, 2022
Fast Swift Views layouting without auto layout. No magic, pure code, full control and blazing fast. Concise syntax, intuitive, readable & chainable. [iOS/macOS/tvOS/CALayer]

Extremely Fast views layouting without auto layout. No magic, pure code, full control and blazing fast. Concise syntax, intuitive, readable & chainabl

layoutBox 2.1k Dec 22, 2022
An easier and faster way to code Autolayout

EZAnchor 中文介绍 An easier way to code Autolayout Are you annoyed of coding .active = true while using Autolayout Anchors over and over again? Are you an

Alex.Liu 25 Feb 20, 2022
The fast path to autolayout views in code

NorthLayout The fast path to autolayout views in code Talks https://speakerdeck.com/banjun/auto-layout-with-an-extended-visual-format-language at AltC

banjun 36 Jul 15, 2022
CompositionalLayoutDSL, library to simplify the creation of UICollectionViewCompositionalLayout. It wraps the UIKit API and makes the code shorter and easier to read.

CompositionalLayoutDSL CompositionalLayoutDSL is a Swift library. It makes easier to create compositional layout for collection view. Requirements Doc

FABERNOVEL 44 Dec 27, 2022
A collection of operators and utilities that simplify iOS layout code.

Anchorage A lightweight collection of intuitive operators and utilities that simplify Auto Layout code. Anchorage is built directly on top of the NSLa

Rightpoint 620 Jan 3, 2023
UIView category which makes it easy to create layout constraints in code

FLKAutoLayout FLKAutoLayout is a collection of categories on UIView which makes it easy to setup layout constraints in code. FLKAutoLayout creates sim

Florian Kugler 1.5k Nov 24, 2022
Written in pure Swift, QuickLayout offers a simple and easy way to manage Auto Layout in code.

QuickLayout QuickLayout offers an additional way, to easily manage the Auto Layout using only code. You can harness the power of QuickLayout to align

Daniel Huri 243 Oct 28, 2022
🎄 Advent of Code ’21 solutions in Swift

Advent of Code '21 My solutions to this years Advent of Code challenge written in Swift. Content Day 1: Sonar Sweep solution Day 2: Dive! solution Day

Witek Bobrowski 2 Dec 1, 2022
This app presents few examples for common patterns using purer SwiftUI code

VIPERtoSwiftUI GOAL This app presents few examples for common patterns using purer (from authors experience) SwiftUI code. LITERATURE https://www.appy

Tomislav Gelešić 0 Dec 19, 2021
A Swift playgrounds with solutions of the Advent of Code 2021 challenge.

?? Advent of Code 2021 ?? A Swift playgrounds with solutions of the Advent of Code 2021. How to run Clone the repo and open the Playground in Xcode. S

Tommaso Madonia 3 Dec 5, 2022
A Code challenge I solved leveraging a lot on Composite collection view layout written in swift

AsthmApp Mobile app designed as a support aid for people with Asthma Accounts Google and Firebase [email protected] dICerytiMPSI Facebook asthmp.ap

null 0 Dec 13, 2021
A Code challenge I solved leveraging a lot on Composite collection view layout...written in swift

Space44 Code Challenge Space44 Code Challenge iOS application for Space 44 hiring process, it leverages on Image download and composite collection vie

null 0 Dec 16, 2021
Fast Swift Views layouting without auto layout. No magic, pure code, full control and blazing fast

Fast Swift Views layouting without auto layout. No magic, pure code, full control and blazing fast. Concise syntax, intuitive, readable & chainable. [iOS/macOS/tvOS/CALayer]

layoutBox 2.1k Jan 2, 2023
Using the UIKitChain framework, You can create a UIKit component in one line of code.

Using the UIKitChain framework, You can create a UIKit component in one line of code. Installation CocoaPods CocoaPods is a dependency manager for Coc

Malith Nadeeshan 1 Sep 1, 2022
CodeEdit App for macOS – Elevate your code editing experience. Open source, free forever.

CodeEdit for macOS CodeEdit is a code editor built by the community, for the community, written entirely and unapologetically for macOS. Features incl

CodeEdit 15.8k Dec 31, 2022
A tool that generate code for Swift projects, designed to improve the maintainability of UIColors

SwiftColorGen A tool that generate code for Swift projects, designed to improve the maintainability of UIColors. Please notice, this tool still under

Fernando del Rio 150 Oct 23, 2022
QR code generator in Swift, with no external dependencies.

QRDispenser is a lightweight library to generate a QR code as image (UIImage) in your app. It uses only native components, with no dependency from oth

Andrea Mario Lufino 12 Nov 17, 2022
An extension that simplifies the work with Swift AutoLayout by writing cleaner, more natural and easy-reading code.

Installation For now you're able to clone repo in your project or download ZIP folder manually. git clone https://github.com/votehserxam/AutoLayout.gi

Max 3 Nov 8, 2022