Skip to content

Instantly share code, notes, and snippets.

@alexrothenberg
Created November 21, 2013 16:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexrothenberg/7584821 to your computer and use it in GitHub Desktop.
Save alexrothenberg/7584821 to your computer and use it in GitHub Desktop.
Convenience methods for dealing with coordinates in RubyMotion
class UIView
def top
frame.origin.y
end
def left
frame.origin.x
end
def height
frame.size.height
end
def width
frame.size.width
end
def bottom
top + height
end
def right
left + width
end
def top=(new_top)
self.frame = [[left, new_top], frame.size]
end
def left=(new_left)
self.frame = [[new_left, top], frame.size]
end
def height=(new_height)
self.frame = [frame.origin, [width, new_height]]
end
def width=(new_width)
self.frame = [frame.origin, [new_width, height]]
end
end
# Create a view
v = UIView.alloc.initWithFrame [[10, 20], [300, 500]]
# => UIView(#e99e820, [[10.0, 20.0], [300.0, 500.0]])
# Use nice convenient accessors instead of the silly verbose v.frame.origin.x or v.frame.size.width
v.left
# => 10.0
v.top
# => 20.0
v.width
# => 300.0
v.height
# => 500.0
v.frame
# => #<CGRect origin=#<CGPoint x=10.0 y=20.0> size=#<CGSize width=300.0 height=500.0>>
# Nice setters to set a single property
v.height = 400
# => 400
v.height
# => 400.0
v.frame
# => #<CGRect origin=#<CGPoint x=10.0 y=20.0> size=#<CGSize width=300.0 height=400.0>>
@markrickert
Copy link

Nice! I'm going to steal this. 👍

@colinta
Copy link

colinta commented Nov 21, 2013

These were merged into SugarCube recently, though I think they're called x/x= and y/y= instead of top/left

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