Last active
December 29, 2015 13:29
-
-
Save libdx/7677643 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ConstraintAttribute | |
attr_reader :name | |
attr_reader :multiplier | |
attr_reader :constraint | |
attr_reader :relation | |
def initialize(constraint, name) | |
@constraint, @name = constraint, name | |
@constant, @multiplier = 0, 1 | |
end | |
def ==(attribute) | |
@constraint.create(attribute, :==) | |
end | |
def <=(attribute) | |
@constraint.create(attribute, :<=) | |
end | |
def >=(attribute) | |
@constraint.create(attribute, :>=) | |
end | |
def *(multiplier) | |
@multiplier = multiplier | |
end | |
def +(constant) | |
@constant = constant | |
end | |
end | |
class Constraint | |
attr_reader :view | |
def initialize(view) | |
@view = view | |
end | |
def create(related_attribute, relation) | |
NSLayoutConstraint.constraintWithItem( | |
@view, | |
attribute:convert_attribute_name(@attribute_name), | |
relatedBy:convert_relation(relation), | |
toItem:related_attribute.constraint.view, | |
attribute:convert_attribute_name(related_attribute.name), | |
multiplier:related_attribute.multiplier, | |
constant:related_attribute.constant | |
) | |
end | |
def convert_relation(symbol) | |
{ | |
:<= => NSLayoutRelationLessThanOrEqual, | |
:== => NSLayoutRelationEqual, | |
:>= => NSLayoutRelationGreaterThanOrEqual | |
}[symbol] | |
end | |
AttributeNamesMap = { | |
left: NSLayoutAttributeLeft, | |
right: NSLayoutAttributeRight, | |
top: NSLayoutAttributeTop, | |
bottom: NSLayoutAttributeBottom, | |
leading: NSLayoutAttributeLeading, | |
trailing: NSLayoutAttributeTrailing, | |
width: NSLayoutAttributeWidth, | |
height: NSLayoutAttributeHeight, | |
center_x: NSLayoutAttributeCenterX, | |
center_y: NSLayoutAttributeCenterY, | |
baseline: NSLayoutAttributeBaseline, | |
none: NSLayoutAttributeNotAnAttribute | |
} | |
def convert_attribute_name(symbol) | |
AttributeNamesMap[symbol] | |
end | |
AttributeNamesMap.keys.each do |key| | |
define_method key, do | |
@attribute = ConstraintAttribute.new(self, key) | |
end | |
end | |
end | |
def constraint(view) | |
Constraint.new(view) | |
end | |
superview = UIView.new | |
view = UIView.new | |
view2 = UIView.new | |
c = constraint(view).width == constraint(view2).height * 1 + 10 | |
superview.addSubview(view) | |
superview.addSubview(view2) | |
superview.addConstraint(c) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment