Skip to content

Instantly share code, notes, and snippets.

@V8tr
Last active October 31, 2023 17:42
Show Gist options
  • Star 63 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save V8tr/3d28b3468bb60b02c5134d8d6ad78c43 to your computer and use it in GitHub Desktop.
Save V8tr/3d28b3468bb60b02c5134d8d6ad78c43 to your computer and use it in GitHub Desktop.
Auto Layout DSL
import UIKit
/// Represents a single `NSLayoutConstraint`
enum LayoutAnchor {
case constant(attribute: NSLayoutConstraint.Attribute,
relation: NSLayoutConstraint.Relation,
constant: CGFloat)
case relative(attribute: NSLayoutConstraint.Attribute,
relation: NSLayoutConstraint.Relation,
relatedTo: NSLayoutConstraint.Attribute,
multiplier: CGFloat,
constant: CGFloat)
}
// MARK: - Factory methods
extension LayoutAnchor {
static let leading = relative(attribute: .leading, relation: .equal, relatedTo: .leading)
static let trailing = relative(attribute: .trailing, relation: .equal, relatedTo: .trailing)
static let top = relative(attribute: .top, relation: .equal, relatedTo: .top)
static let bottom = relative(attribute: .bottom, relation: .equal, relatedTo: .bottom)
static let centerX = relative(attribute: .centerX, relation: .equal, relatedTo: .centerX)
static let centerY = relative(attribute: .centerY, relation: .equal, relatedTo: .centerY)
static let width = constant(attribute: .width, relation: .equal)
static let height = constant(attribute: .height, relation: .equal)
static func constant(
attribute: NSLayoutConstraint.Attribute,
relation: NSLayoutConstraint.Relation
) -> (CGFloat) -> LayoutAnchor {
return { constant in
.constant(attribute: attribute, relation: relation, constant: constant)
}
}
static func relative(
attribute: NSLayoutConstraint.Attribute,
relation: NSLayoutConstraint.Relation,
relatedTo: NSLayoutConstraint.Attribute,
multiplier: CGFloat = 1
) -> (CGFloat) -> LayoutAnchor {
return { constant in
.relative(attribute: attribute, relation: relation, relatedTo: relatedTo, multiplier: multiplier, constant: constant)
}
}
}
// MARK: - Conveniences
extension UIView {
func addSubview(_ subview: UIView, anchors: [LayoutAnchor]) {
subview.translatesAutoresizingMaskIntoConstraints = false
addSubview(subview)
subview.activate(anchors: anchors, relativeTo: self)
}
func activate(anchors: [LayoutAnchor], relativeTo item: UIView? = nil) {
let constraints = anchors.map { NSLayoutConstraint(from: self, to: item, anchor: $0) }
NSLayoutConstraint.activate(constraints)
}
}
extension NSLayoutConstraint {
convenience init(from: UIView, to item: UIView?, anchor: LayoutAnchor) {
switch anchor {
case let .constant(attribute: attr, relation: relation, constant: constant):
self.init(
item: from,
attribute: attr,
relatedBy: relation,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: constant
)
case let .relative(attribute: attr,
relation: relation,
relatedTo: relatedTo,
multiplier: multiplier,
constant: constant):
self.init(
item: from,
attribute: attr,
relatedBy: relation,
toItem: item,
attribute: relatedTo,
multiplier: multiplier,
constant: constant
)
}
}
}
import UIKit
class ExampleViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let yellow = UIView()
yellow.backgroundColor = .yellow
view.addSubview(yellow, anchors: [.leading(0), .trailing(0), .bottom(0), .top(0)])
let redBox = UIView()
redBox.backgroundColor = .red
view.addSubview(redBox, anchors: [.centerX(0), .centerY(0), .width(100), .height(100)])
}
}

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.

In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.

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 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.

For more information, please refer to https://unlicense.org

@vburojevic
Copy link

What if you need to pin something to the safeAreaLayoutGuide?

@hamzausmani-674
Copy link

What if you need to pin something to the safeAreaLayoutGuide?

did you find the solution ?

@prokhorovxo
Copy link

prokhorovxo commented Feb 13, 2022

@vburojevic @devhamza97

This is my approach:

1. Add new case in LayoutAnchor

case relativeSafeArea(attribute: NSLayoutConstraint.Attribute,
                          relation: NSLayoutConstraint.Relation,
                          relatedTo: NSLayoutConstraint.Attribute,
                          multiplier: CGFloat,
                          constant: CGFloat)

2. Add new method in LayoutAnchor

    static func relativeSafeArea(attribute: NSLayoutConstraint.Attribute,
                                 relation: NSLayoutConstraint.Relation,
                                 relatedTo: NSLayoutConstraint.Attribute,
                                 multiplier: CGFloat = 1.0) -> (CGFloat) -> LayoutDSLAnchor {
        return { constant in
                .relativeSafeArea(attribute: attribute,
                                  relation: relation,
                                  relatedTo: relatedTo,
                                  multiplier: multiplier,
                                  constant: constant)
        }
    }

3. Handle new case in convenience init NSLayoutConstraint

case let .relativeSafeArea(attribute: attr,
                                   relation: relation,
                                   relatedTo: relatedTo,
                                   multiplier: multiplier,
                                   constant: constant):
            guard let safeAreaLayoutGuide = item?.safeAreaLayoutGuide
            else { fatalError("\(String(describing: item)) safeAreaLayoutGuide problem") }
            
            self.init(item: from,
                      attribute: attr,
                      relatedBy: relation,
                      toItem: safeAreaLayoutGuide,
                      attribute: relatedTo,
                      multiplier: multiplier,
                      constant: constant)

4. And finally add new static properties in LayoutAnchor

static let leadingSafeArea = relativeSafeArea(attribute: .leading, relation: .equal, relatedTo: .leading)
static let trailingSafeArea = relativeSafeArea(attribute: .trailing, relation: .equal, relatedTo: .trailing)
static let topSafeArea = relativeSafeArea(attribute: .top, relation: .equal, relatedTo: .top)
static let bottomSafeArea = relativeSafeArea(attribute: .bottom, relation: .equal, relatedTo: .bottom)

@nikitatroin
Copy link

@prokhorovxo
Copy link

@nikitatroin you forgot to use value binding

Screenshot 2022-02-22 at 20 10 39

@nikitatroin
Copy link

@prokhorovxo Oh, thanks man!

@KarthikSaminathan
Copy link

It helped me lot. How i can update the existing layoutanchor? like the same top layoutanchor value needs to be change in the landscape mode? please help

@sanket2126
Copy link

What if we want to give aspect ratio to any view ?

  • Suppose if we want to assign same width to any view as per the view height arranged in Stackview.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment