/ gist

15. Swift gist: NSLayoutConstraint+Init.swift

This gist was very helpful in the past, but now we have layout anchors, so I don't really need it anymore. One of the next posts is going to be all about the history of layout methods, so let's start to tune in with "my old snippet".

#if os(iOS) || os(tvOS)
    import UIKit.NSLayoutConstraint
    public typealias AppleView = UIView
#elseif os(OSX)
    import AppKit.NSLayoutConstraint
    public typealias AppleView = NSView

#if os(iOS) || os(tvOS) || os(OSX)
    import CoreGraphics
    public enum LayoutRelation : Int
        case Less
        case Equal
        case Greater
        public var NSLayoutRelationValue : NSLayoutRelation {
            switch self {
            case .Less:
                return .lessThanOrEqual
            case .Greater:
                return .greaterThanOrEqual
                return .equal
    public extension NSLayoutConstraint
        public convenience init(_ item: AppleView,
                                _ attr1: NSLayoutAttribute,
                                _ relatedBy: LayoutRelation = .Equal,
                                to toItem: AppleView? = nil,
                                _ attr2: NSLayoutAttribute? = nil,
                                multiplier: CGFloat = 1.0,
                                constant: CGFloat = 0.0)
            var attr = attr2
            if attr == nil {
                attr = attr1
            self.init(item: item,
                      attribute: attr1,
                      relatedBy: relatedBy.NSLayoutRelationValue,
                      toItem: toItem,
                      attribute: attr!,
                      multiplier: multiplier,
                      constant: constant)