Skip to content

Instantly share code, notes, and snippets.

@raulriera
Created October 23, 2015 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raulriera/97d20df0a867a445e313 to your computer and use it in GitHub Desktop.
Save raulriera/97d20df0a867a445e313 to your computer and use it in GitHub Desktop.
Sometimes I just want to get a given constraint
//
// UIViewExtensions.swift
//
// Created by Raúl Riera on 23/09/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
extension UIView {
/**
Returns the matching attribute constraint held by the view.
- parameter attribute: attribute of the constraint
- returns: the matching constraint
*/
public func layoutConstraint(attribute attribute: NSLayoutAttribute) -> NSLayoutConstraint? {
return layoutConstraints(attributes: [attribute]).first
}
/**
Returns the matching attribute constraints held by the view.
- parameter attribute: of the constraints
- returns: the matching constraints
*/
public func layoutConstraints(attribute attribute: NSLayoutAttribute) -> [NSLayoutConstraint] {
return layoutConstraints(attributes: [attribute])
}
/**
Returns the matching attributes constraints held by the view.
- parameter attributes: array of attributes of the constraints
- returns: the matching constraints
*/
public func layoutConstraints(attributes attributes: [NSLayoutAttribute]) -> [NSLayoutConstraint] {
var layoutConstraints = [NSLayoutConstraint]()
if let superviewConstrains = superview?.constraints {
layoutConstraints += superviewConstrains
}
layoutConstraints += constraints
let filteredConstraints = layoutConstraints.filter { (layoutConstraint) in
return attributes.contains(layoutConstraint.firstAttribute)
}.filter { (layoutConstraint) in
if let secondItem: AnyObject = layoutConstraint.secondItem {
return layoutConstraint.firstItem.isEqual(self) || secondItem.isEqual(self)
} else {
return layoutConstraint.firstItem.isEqual(self)
}
}
return filteredConstraints
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment