{"id":1306,"url":"https://github.com/DeclarativeHub/Layoutless","last_synced_at":"2025-08-06T13:32:41.403Z","repository":{"id":53511239,"uuid":"120192874","full_name":"DeclarativeHub/Layoutless","owner":"DeclarativeHub","description":"Write less UI code","archived":false,"fork":false,"pushed_at":"2021-03-26T20:49:46.000Z","size":781,"stargazers_count":432,"open_issues_count":5,"forks_count":25,"subscribers_count":7,"default_branch":"master","last_synced_at":"2024-12-08T09:31:22.901Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DeclarativeHub.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-02-04T14:38:35.000Z","updated_at":"2024-10-16T10:05:06.000Z","dependencies_parsed_at":"2022-08-26T13:41:12.251Z","dependency_job_id":null,"html_url":"https://github.com/DeclarativeHub/Layoutless","commit_stats":null,"previous_names":[],"tags_count":13,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DeclarativeHub%2FLayoutless","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DeclarativeHub%2FLayoutless/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DeclarativeHub%2FLayoutless/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DeclarativeHub%2FLayoutless/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DeclarativeHub","download_url":"https://codeload.github.com/DeclarativeHub/Layoutless/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228905503,"owners_count":17989778,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-01-05T20:15:43.417Z","updated_at":"2024-12-09T14:31:01.873Z","avatar_url":"https://github.com/DeclarativeHub.png","language":"Swift","funding_links":[],"categories":["Layout","Libs","Layout [🔝](#readme)"],"sub_categories":["Other Hardware","Layout","Other free courses"],"readme":"[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](#carthage)\n[![Platform](https://img.shields.io/cocoapods/p/Layoutless.svg?style=flat)](http://cocoadocs.org/docsets/Layoutless/)\n[![Twitter](https://img.shields.io/badge/twitter-@srdanrasic-red.svg?style=flat)](https://twitter.com/srdanrasic)\n\n# Layoutless\n\nLayoutless 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:\n\n\u003cimg src=\"Assets/profile@2x.png\" align=\"right\" width=\"200px\" hspace=\"30px\" vspace=\"0px\"\u003e\n\n```swift\nclass ProfileView: View {\n\n    let imageView = UIImageView(style: Stylesheet.profileImage)\n    let nameLabel = UILabel(style: Stylesheet.profileName)\n\n    override var subviewsLayout: AnyLayout {\n        return stack(.vertical, alignment: .center)(\n            imageView,\n            nameLabel\n        ).fillingParent(insets: 12)\n    }\n}\n```\n\nLayoutless 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.\n\nThere are three main features of Layoutless.\n\n## Layout Patterns\n\nIn 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.\n\n### Basic Patterns\n\n\u003cimg src=\"Assets/patterns@2x.png\" width=\"860px\"\u003e\n\n### Walkthrough\n\nImagine 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: \n\n```swift\nlet imageView = UIImageView()\nlet bodyLabel = UILabel()\n```\n\nLet 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.\n\nFor example, to stack our two views vertically, we can use `stack` function:\n\n```swift\nlet layout = stack(.vertical)(\n    imageView,\n    bodyLabel\n)\n```\n\nNext, 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:\n\n```swift\nlet layout = stack(.vertical)(\n    imageView,\n    bodyLabel.insetting(left: 18, right: 18)\n)\n```\n\nAll 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:\n\n```swift\nlet layout = stack(.vertical)(\n    imageView,\n    bodyLabel.insetting(left: 18, right: 18)\n).scrolling(.vertical)\n```\n\nNow 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:\n\n```swift\nlet layout = stack(.vertical)(\n    imageView,\n    bodyLabel.insetting(left: 18, right: 18)\n).scrolling(.vertical).fillingParent()\n```\n\nWhat 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:\n\n```swift\nlayout.layout(in: parentView)\n```\n\nAnd 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](https://github.com/DeclarativeHub/Layoutless/blob/master/Sources/Layout/Layoutless.swift). 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.\n\nKeep reading if you wish things were even simpler. \n\n## Base Views\n\nBuilding 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.\n\nWhat 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:\n\n\u003cimg src=\"Assets/article@2x.png\" align=\"left\" width=\"200px\" hspace=\"20px\" vspace=\"20px\"\u003e\n\n```swift\nclass ArticleView: View { // or ArticleViewController: ViewController\n\n    let imageView = UIImageView()\n    let bodyLabel = UILabel()\n\n    override var subviewsLayout: AnyLayout {\n        return stack(.vertical)(\n            imageView,\n            bodyLabel.insetting(left: 18, right: 18)\n        ).scrolling(.vertical).fillingParent()\n    }\n}\n```\n\n`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](https://github.com/DeclarativeHub/Layoutless/blob/master/Sources/Views/View.swift).\n\nLayoutless provides base views like: `View`, `Control`, `Label`, `Button`, `ImageView`, `TextField`, etc.\n\n## Styling \n\nFor 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](https://hackernoon.com/simple-stylesheets-in-swift-6dda57b5b00d), so let's just see how it works.\n\nWe 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.\n\n```swift\nextension ArticleView {\n\n    enum Stylesheet {\n\n        static let image = Style\u003cUIImageView\u003e {\n            $0.contentMode = .center\n            $0.backgroundColor = .lightGray\n        }\n\n        static let body = Style\u003cUILabel\u003e {\n            $0.font = .systemFont(ofSize: 14)\n            $0.textColor = .black\n        }\n    }\n}\n```\n\nAs 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.\n\nTo use our styles, we will just instantiate our views using the convenience initializers provided by the framework:\n\n```swift\nclass ArticleView: View {\n\n    let imageView = UIImageView(style: Stylesheet.image)\n    let bodyLabel = UILabel(style: Stylesheet.body)\n\n    ...\n}\n```\n\n😍\n\n## Advanced \n\n### Layout Sets\n\nUniversal 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. \n\nLayoutless 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.\nJust 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:\n\n```swift\nclass MyViewController: ViewController {\n\n    override var subviewsLayout: AnyLayout {\n\n        let portrait: AnyLayout = ...\n        let landscape: AnyLayout = ...\n\n        return layoutSet(\n            traitQuery(traitCollection: UITraitCollection(horizontalSizeClass: .compact)) { portrait },\n            traitQuery(traitCollection: UITraitCollection(horizontalSizeClass: .regular)) { landscape }\n        )\n    }\n}\n```\n\nAs 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:\n\n```swift\nlayoutSet(\n    traitQuery(width: .lessThanOrEqual(1000)) { ... },\n    traitQuery(width: .greaterThanOrEqual(1000)) { ... }\n)\n```\n\nQuery trait sets should be disjunct sets. \n\nNote that app's key window must be Layoutless `Window` or its subclass for the dynamic layout change to work.\n\n## Requirements\n\n* iOS 9.0+ / tvOS 9.0+\n* Xcode 9\n\n## Installation\n\n### Carthage\n\n```\ngithub \"DeclarativeHub/Layoutless\"\n```\n\n### CocoaPods\n\n```\npod 'Layoutless'\n```\n\n## Communication\n\n* If you would like to ask a general question, open a question issue.\n* If you have found a bug, open an issue or do a pull request with the fix.\n* If you have a feature request, open an issue with the proposal.\n* If you want to contribute, submit a pull request (include unit tests).\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2017-2018 Srdan Rasic (@srdanrasic)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDeclarativeHub%2FLayoutless","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FDeclarativeHub%2FLayoutless","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDeclarativeHub%2FLayoutless/lists"}