Class: UIView

Inherits:
Object show all
Defined in:
lib/sugarcube-gestures/gestures.rb,
lib/sugarcube-pipes/pipes.rb,
lib/sugarcube-to_s/uiview.rb,
lib/sugarcube-uikit/uiview.rb,
lib/sugarcube-animations/uiview.rb,
lib/sugarcube/sugarcube_cleanup.rb

Overview

BubbleWrap has these same methods, but the logic and options are a little different. In the spirit of open source, I am blatantly copying their code, changing it to suit my needs, and offering it here

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.animate(options = {}, more_options = {}, &animations) ⇒ Object

If options is a Numeric, it is used as the duration. Otherwise, duration is an option, and defaults to 0.3. All the transition methods work this way.

Options Hash (options):

  • :duration (Float)

    Animation duration. default: 0.3

  • :delay (Float)

    Delay before animations begin. default: 0

  • :damping (Float)

    Enables the "spring" animation. Value of 1.0 is a stiff spring.

  • :velocity (Float)

    Used in a spring animation to set the initial velocity

  • :after (Proc)

    A block that is executed when the animation is complete, useful for chaining (though the animation_chain method is better!)

  • :options (Fixnum)

    The options parameter that is passed to the UIView.animateWithDuration(...) method. You can also use the more verbose options :curve, :from_current, and :allow_interaction

  • :curve (Fixnum)

    The animation curve option. default: UIViewAnimationOptionCurveEaseIn

  • :from_current (Boolean)

    Whether or not to have animations start from their current position (aka UIViewAnimationOptionBeginFromCurrentState)

  • :allow_interaction (Boolean)

    aka UIViewAnimationOptionAllowUserInteraction



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/sugarcube-animations/uiview.rb', line 17

def animate(options={}, more_options={}, &animations)
  raise "animation block is required" unless animations

  if options.is_a? Numeric
    duration = options
    options = more_options
  else
    duration = options[:duration] || 0.3
  end

  delay = options[:delay] || 0

  damping_ratio = options[:damping] || nil
  spring_velocity = options[:velocity] || 0.0

  # chain: true is used inside animation_chain blocks to prevent some weird
  # animation errors (nested animations do not delay/queue as you'd expect)
  if options[:chain] || Thread.current[:sugarcube_chaining]
    duration = 0
    delay = 0
    raise "Completion blocks cannot be used within an animation_chain block" if options[:after]
  end

  after_animations = options[:after]
  if after_animations
    if after_animations.arity == 0
      after_adjusted = ->(finished){ after_animations.call }
    else
      after_adjusted = after_animations
    end
  else
    after_adjusted = nil
  end

  animation_options = options[:options]
  unless animation_options
    curve = options.fetch(:curve, UIViewAnimationOptionCurveEaseInOut)
    curve = curve.uianimationcurve if curve.is_a?(Symbol)

    from_current = options.fetch(:from_current, true) ? UIViewAnimationOptionBeginFromCurrentState : 0
    allow_interaction = options.fetch(:allow_interaction, false) ? UIViewAnimationOptionAllowUserInteraction : 0

    animation_options = curve | from_current
  end

  if duration == 0 && delay == 0
    animations.call
    after_adjusted.call(true) if after_adjusted
  else
    prev_value = Thread.current[:sugarcube_chaining]
    Thread.current[:sugarcube_chaining] = true

    if damping_ratio
      UIView.animateWithDuration( duration,
                           delay: delay,
          usingSpringWithDamping: damping_ratio,
           initialSpringVelocity: spring_velocity,
                         options: animation_options,
                      animations: animations,
                      completion: after_adjusted
                                )
    else
      UIView.animateWithDuration( duration,
                           delay: delay,
                         options: animation_options,
                      animations: animations,
                      completion: after_adjusted
                                )
    end
    Thread.current[:sugarcube_chaining] = prev_value
  end
  nil
end

.animation_chain(options = {}, &first) ⇒ Object

Animation chains are great for consecutive animation blocks. Each chain can take the same options that UIView##animate take.



93
94
95
96
97
98
99
# File 'lib/sugarcube-animations/uiview.rb', line 93

def animation_chain(options={}, &first)
  chain = SugarCube::AnimationChain.new
  if first
    chain.and_then(options, &first)
  end
  return chain
end

.attr_updates(*attrs) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/sugarcube-uikit/uiview.rb', line 10

def attr_updates(*attrs)
  attr_accessor(*attrs)
  attrs.each do |attr|
    define_method("#{attr}=") do |value|
      if instance_variable_get("@#{attr}") != value
        setNeedsDisplay
      end
      instance_variable_set("@#{attr}", value)
    end
  end
end

.first_responderObject

returns the first responder, starting at the Window and searching every subview



6
7
8
# File 'lib/sugarcube-uikit/uiview.rb', line 6

def first_responder
  UIApplication.sharedApplication.keyWindow.first_responder
end

Instance Method Details

#<<(view) ⇒ Object

superview << view => superview.addSubview(view)



26
27
28
29
# File 'lib/sugarcube-uikit/uiview.rb', line 26

def <<(view)
  self.addSubview(view)
  return self
end

#animate(options = {}, more_options = {}, &animations) ⇒ Object

Same as UIView##animate, but acts on self



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/sugarcube-animations/uiview.rb', line 114

def animate(options={}, more_options={}, &animations)
  if options.is_a? Numeric
    options = more_options.merge(duration: options)
  end

  assign = options[:assign] || {}

  UIView.animate(options) do
    animations.call if animations

    assign.each do |key, value|
      self.send("#{key}=", value)
    end
  end
  return self
end

#back_fiend!(options = {}, more_options = {}) ⇒ Object

Moves the view backwards, similar to what Google has been doing a lot recently



526
527
528
529
530
531
532
533
534
535
536
# File 'lib/sugarcube-animations/uiview.rb', line 526

def back_fiend!(options={}, more_options={})
  scale = options[:scale] || 0.5
  perspective = options[:perspective] || -0.0005
  size = options[:size] || -140

  UIView.animation_chain(duration:200.millisecs, options:UIViewAnimationOptionCurveLinear) {
    self.layer.transform = CATransform3DTranslate(CATransform3DScale(CATransform3D.new(1,0,0,0, 0,1,0,perspective, 0,0,1,0, 0,0,0,1), scale, scale, scale), 0, size, 0)
  }.and_then(duration:300.millisecs, options:UIViewAnimationOptionCurveLinear) {
    self.layer.transform = CATransform3DTranslate(CATransform3DScale(CATransform3DIdentity, scale, scale, scale), 0, size, 0)
  }.start
end

#center_to(center, options = {}, more_options = {}, &after) ⇒ Object



209
210
211
212
213
214
215
216
217
218
219
# File 'lib/sugarcube-animations/uiview.rb', line 209

def center_to(center, options={}, more_options={}, &after)
  if options.is_a? Numeric
    options = more_options.merge(duration: options)
  end

  options[:after] = after

  animate(options) {
    self.center = SugarCube::CoreGraphics::Point(center)
  }
end

#controllerObject

returns the nearest nextResponder instance that is a UIViewController. Goes up the responder chain until the nextResponder is a UIViewController subclass, or returns nil if none is found.



54
55
56
57
58
59
60
61
62
# File 'lib/sugarcube-uikit/uiview.rb', line 54

def controller
  if nextResponder.is_a?(UIViewController)
    nextResponder
  elsif nextResponder.is_a?(UIView)
    nextResponder.controller
  else
    nil
  end
end

#convert_bounds(destination) ⇒ Object

Returns the receiver's bounds in the coordinate system of destination



101
102
103
104
105
106
107
108
109
# File 'lib/sugarcube-uikit/uiview.rb', line 101

def convert_bounds(destination)
  message = "The (ambiguously named) `convert_bounds` method has been deprecated, use `convert_frame_to` (or `convert_frame_from`)"
  if defined?(SugarCube::Legacy)
    SugarCube::Legacy.log(message)
  else
    NSLog(message)
  end
  return convert_frame_to(destination)
end

#convert_frame_from(source) ⇒ Object



115
116
117
# File 'lib/sugarcube-uikit/uiview.rb', line 115

def convert_frame_from(source)
  return self.convert_rect(CGRectMake(0, 0, source.frame.size.width, source.frame.size.height), from: source)
end

#convert_frame_to(destination) ⇒ Object



111
112
113
# File 'lib/sugarcube-uikit/uiview.rb', line 111

def convert_frame_to(destination)
  return self.convert_rect(CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), to: destination)
end

#convert_origin(destination) ⇒ Object

Returns the receiver's bounds in the coordinate system of destination



128
129
130
131
132
133
134
135
136
# File 'lib/sugarcube-uikit/uiview.rb', line 128

def convert_origin(destination)
  message = "The (ambiguously named) `convert_origin` method has been deprecated, use `convert_origin_to` (or `convert_origin_from`)"
  if defined?(SugarCube::Legacy)
    SugarCube::Legacy.log(message)
  else
    NSLog(message)
  end
  return self.convert_origin_to(destination)
end

#convert_origin_from(source) ⇒ Object



150
151
152
# File 'lib/sugarcube-uikit/uiview.rb', line 150

def convert_origin_from(source)
  return self.convert_point([0, 0], from: source)
end

#convert_origin_to(destination) ⇒ Object



146
147
148
# File 'lib/sugarcube-uikit/uiview.rb', line 146

def convert_origin_to(destination)
  return self.convert_point([0, 0], to: destination)
end

#convert_point(point, from: source) ⇒ Object



138
139
140
# File 'lib/sugarcube-uikit/uiview.rb', line 138

def convert_point(point, to: destination)
  return self.convertPoint(point, toView: destination)
end

#convert_rect(rect, from: source) ⇒ Object



119
120
121
# File 'lib/sugarcube-uikit/uiview.rb', line 119

def convert_rect(rect, to: destination)
  return self.convertRect(rect, toView: destination)
end

#delta_to(delta, options = {}, more_options = {}, &after) ⇒ Object



235
236
237
238
239
240
241
242
# File 'lib/sugarcube-animations/uiview.rb', line 235

def delta_to(delta, options={}, more_options={}, &after)
  f = self.frame
  delta = SugarCube::CoreGraphics::Point(delta)
  position = SugarCube::CoreGraphics::Point(f.origin)
  to_position = CGPoint.new(position.x + delta.x, position.y + delta.y)
  move_to(to_position, options, more_options, &after)
  return self
end

#fade(options = {}, more_options = {}, &after) ⇒ Object

Changes the layer opacity.



132
133
134
135
136
137
138
139
140
141
142
# File 'lib/sugarcube-animations/uiview.rb', line 132

def fade(options={}, more_options={}, &after)
  if options.is_a? Numeric
    options = { opacity: options }
  end

  options[:after] = after

  animate(options) do
    self.alpha = options[:opacity]
  end
end

#fade_in(options = {}, more_options = {}, &after) ⇒ Object

Changes the layer opacity to 1.

See Also:



158
159
160
161
162
163
164
165
166
# File 'lib/sugarcube-animations/uiview.rb', line 158

def fade_in(options={}, more_options={}, &after)
  if options.is_a? Numeric
    options = more_options.merge(duration: options)
  end

  options[:opacity] ||= 1.0

  fade(options, &after)
end

#fade_out(options = {}, more_options = {}, &after) ⇒ Object

Changes the layer opacity to 0.

See Also:



146
147
148
149
150
151
152
153
154
# File 'lib/sugarcube-animations/uiview.rb', line 146

def fade_out(options={}, more_options={}, &after)
  if options.is_a? Numeric
    options = more_options.merge(duration: options)
  end

  options[:opacity] ||= 0.0

  fade(options, &after)
end

#fade_out_and_remove(options = {}, more_options = {}, &after) ⇒ Object

Changes the layer opacity to 0 and then removes the view from its superview

See Also:



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/sugarcube-animations/uiview.rb', line 170

def fade_out_and_remove(options={}, more_options={}, &after)
  if options.is_a? Numeric
    options = more_options.merge(duration: options)
  end

  original_opacity = self.alpha

  after_remove = proc do
    self.alpha = original_opacity
    removeFromSuperview
    after.call if after
  end

  fade_out(options, &after_remove)
end

#first_responderObject

returns the first responder, or nil if it cannot be found



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/sugarcube-uikit/uiview.rb', line 37

def first_responder
  if self.firstResponder?
    return self
  end

  found = nil
  self.subviews.each do |subview|
    found = subview.first_responder
    break if found
  end

  return found
end

#forward_fiend!(options = {}, more_options = {}) ⇒ Object

restores the layer after a call to 'back_fiend!'



539
540
541
542
543
# File 'lib/sugarcube-animations/uiview.rb', line 539

def forward_fiend!(options={}, more_options={})
  UIView.animate(options) do
    self.layer.transform = CATransform3DIdentity
  end
end

#heightObject



176
177
178
# File 'lib/sugarcube-uikit/uiview.rb', line 176

def height
  self.frame.size.height
end

#hideObject



108
109
110
111
# File 'lib/sugarcube-animations/uiview.rb', line 108

def hide
  self.hidden = true
  return self
end

#move_to(position, options = {}, more_options = {}, &after) ⇒ Object



221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/sugarcube-animations/uiview.rb', line 221

def move_to(position, options={}, more_options={}, &after)
  if options.is_a? Numeric
    options = more_options.merge(duration: options)
  end

  options[:after] = after

  animate(options) do
    f = self.frame
    f.origin = SugarCube::CoreGraphics::Point(position)
    self.frame = f
  end
end

#off_gesturesObject



33
34
35
36
37
38
39
40
41
42
# File 'lib/sugarcube-gestures/gestures.rb', line 33

def off_gestures
  if @sugarcube_recognizers
    @sugarcube_recognizers.each do |recognizer, proc|
      self.removeGestureRecognizer(recognizer)
    end
    @sugarcube_recognizers = nil
  end

  self
end

#on_gesture(recognizer) ⇒ Object #on_gesture(recognizer_class) ⇒ Object

A generic gesture adder, but accepts a block like the other gesture methods

Examples:

Using a UIGestureRecognizer class

view.on_gesture(UISwipeGestureRecognizer, direction: UISwipeGestureRecognizerDirectionLeft) { puts "swiped left" }

Using a UIGestureRecognizer instance

gesture = UISwipeGestureRecognizer
gesture.direction = UISwipeGestureRecognizerDirectionLeft
view.on_gesture(gesture) { puts "swiped left" }

Overloads:

  • #on_gesture(recognizer) ⇒ Object

    Adds the gesture to the view, and yields the block when the gesture is recognized

  • #on_gesture(recognizer_class) ⇒ Object

    Instantiates a gesture and adds it to the view.

Yields:

  • (recognizer)

    Handles the gesture event, and passes the recognizer instance to the block.



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/sugarcube-gestures/gestures.rb', line 19

def on_gesture(klass, options={}, &proc)
  if klass.is_a? UIGestureRecognizer
    recognizer = klass
    recognizer.addTarget(self, action:'sugarcube_handle_gesture:')
  else
    recognizer = klass.alloc.initWithTarget(self, action:'sugarcube_handle_gesture:')
  end

  options.each do |method, value|
    recognizer.send(method, value)
  end
  sugarcube_add_gesture(proc, recognizer)
end

#on_tap(taps) ⇒ Object #on_tap(options) ⇒ Object

Overloads:

  • #on_tap(options) ⇒ Object

    Options Hash (options):

    • :min_fingers (Fixnum)

      Minimum number of fingers for gesture to be recognized

    • :max_fingers (Fixnum)

      Maximum number of fingers for gesture to be recognized

    • :fingers (Fixnum)

      If min_fingers or max_fingers is not assigned, this will be the default.

Yields:

  • (recognizer)

    Handles the gesture event, and passes the recognizer instance to the block.



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/sugarcube-gestures/gestures.rb', line 124

def on_pan(fingers_or_options=nil, &proc)
  fingers = nil
  min_fingers = nil
  max_fingers = nil

  if fingers_or_options
    if fingers_or_options.is_a? Hash
      fingers = fingers_or_options[:fingers] || fingers
      min_fingers = fingers_or_options[:min_fingers] || min_fingers
      max_fingers = fingers_or_options[:max_fingers] || max_fingers
    else
      fingers = fingers_or_options
    end
  end

  # if fingers is assigned, but not min/max, assign it as a default
  min_fingers ||= fingers
  max_fingers ||= fingers

  recognizer = UIPanGestureRecognizer.alloc.initWithTarget(self, action:'sugarcube_handle_gesture:')
  recognizer.maximumNumberOfTouches = min_fingers if min_fingers
  recognizer.minimumNumberOfTouches = max_fingers if max_fingers
  sugarcube_add_gesture(proc, recognizer)
end

#on_pinch {|recognizer| ... } ⇒ Object

Yields:

  • (recognizer)

    Handles the gesture event, and passes the recognizer instance to the block.



70
71
72
73
# File 'lib/sugarcube-gestures/gestures.rb', line 70

def on_pinch(&proc)
  recognizer = UIPinchGestureRecognizer.alloc.initWithTarget(self, action:'sugarcube_handle_gesture:')
  sugarcube_add_gesture(proc, recognizer)
end

#on_press(duration) ⇒ Object #on_tap(options) ⇒ Object

Overloads:

  • #on_tap(options) ⇒ Object

    Options Hash (options):

    • :duration (Fixnum)

      How long in seconds before gesture is recognized

    • :taps (Fixnum)

      Number of taps before gesture is recognized

    • :fingers (Fixnum)

      Number of fingers before gesture is recognized

Yields:

  • (recognizer)

    Handles the gesture event, and passes the recognizer instance to the block.



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/sugarcube-gestures/gestures.rb', line 156

def on_press(duration_or_options=nil, &proc)
  duration = nil
  taps = nil
  fingers = nil

  if duration_or_options
    if duration_or_options.is_a? Hash
      duration = duration_or_options[:duration] || duration
      taps = duration_or_options[:taps] || taps
      fingers = duration_or_options[:fingers] || fingers
    else
      duration = duration_or_options
    end
  end

  recognizer = UILongPressGestureRecognizer.alloc.initWithTarget(self, action:'sugarcube_handle_gesture:')
  recognizer.minimumPressDuration = duration if duration
  recognizer.numberOfTapsRequired = taps if taps
  recognizer.numberOfTouchesRequired = fingers if fingers
  sugarcube_add_gesture(proc, recognizer)
end

#on_press_begin(duration_or_options = nil, &proc) ⇒ Object



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/sugarcube-gestures/gestures.rb', line 178

def on_press_begin(duration_or_options=nil, &proc)
  duration = nil
  taps = nil
  fingers = nil

  if duration_or_options
    if duration_or_options.is_a? Hash
      duration = duration_or_options[:duration] || duration
      taps = duration_or_options[:taps] || taps
      fingers = duration_or_options[:fingers] || fingers
    else
      duration = duration_or_options
    end
  end

  recognizer = UILongPressGestureRecognizer.alloc.initWithTarget(self, action:'sugarcube_handle_gesture_long_press_on_begin:')
  recognizer.minimumPressDuration = duration if duration
  recognizer.numberOfTapsRequired = taps if taps
  recognizer.numberOfTouchesRequired = fingers if fingers
  sugarcube_add_gesture(proc, recognizer)
end

#on_rotate {|recognizer| ... } ⇒ Object

Yields:

  • (recognizer)

    Handles the gesture event, and passes the recognizer instance to the block.



76
77
78
79
# File 'lib/sugarcube-gestures/gestures.rb', line 76

def on_rotate(&proc)
  recognizer = UIRotationGestureRecognizer.alloc.initWithTarget(self, action:'sugarcube_handle_gesture:')
  sugarcube_add_gesture(proc, recognizer)
end

#on_swipe(taps) ⇒ Object #on_swipe(options) ⇒ Object

Overloads:

  • #on_swipe(options) ⇒ Object

    Options Hash (options):

    • :fingers (Fixnum)

      Number of fingers before gesture is recognized

    • :direction (Fixnum, Symbol)

      Direction of swipe, as a UISwipeGestureRecognizerDirection constant or a symbol (:left, :right, :up, :down)

Yields:

  • (recognizer)

    Handles the gesture event, and passes the recognizer instance to the block.



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/sugarcube-gestures/gestures.rb', line 87

def on_swipe(direction_or_options, &proc)
  direction = nil
  fingers = nil

  if direction_or_options
    if direction_or_options.is_a? Hash
      direction = direction_or_options[:direction] || direction
      fingers = direction_or_options[:fingers] || fingers
    else
      direction = direction_or_options
    end
  end

  case direction
  when :left
    direction = UISwipeGestureRecognizerDirectionLeft
  when :right
    direction = UISwipeGestureRecognizerDirectionRight
  when :up
    direction = UISwipeGestureRecognizerDirectionUp
  when :down
    direction = UISwipeGestureRecognizerDirectionDown
  end

  recognizer = UISwipeGestureRecognizer.alloc.initWithTarget(self, action:'sugarcube_handle_gesture:')
  recognizer.direction = direction if direction
  recognizer.numberOfTouchesRequired = fingers if fingers
  sugarcube_add_gesture(proc, recognizer)
end

#on_tap(taps) ⇒ Object #on_tap(options) ⇒ Object

Overloads:

  • #on_tap(options) ⇒ Object

    Options Hash (options):

    • :taps (Fixnum)

      Number of taps before gesture is recognized

    • :fingers (Fixnum)

      Number of fingers before gesture is recognized

Yields:

  • (recognizer)

    Handles the gesture event, and passes the recognizer instance to the block.



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/sugarcube-gestures/gestures.rb', line 50

def on_tap(taps_or_options=nil, &proc)
  taps = nil
  fingers = nil

  if taps_or_options
    if taps_or_options.is_a? Hash
      taps = taps_or_options[:taps] || taps
      fingers = taps_or_options[:fingers] || fingers
    else
      taps = taps_or_options
    end
  end

  recognizer = UITapGestureRecognizer.alloc.initWithTarget(self, action:'sugarcube_handle_gesture:')
  recognizer.numberOfTapsRequired = taps if taps
  recognizer.numberOfTouchesRequired = fingers if fingers
  sugarcube_add_gesture(proc, recognizer)
end

#reframe_to(frame, options = {}, more_options = {}, &after) ⇒ Object



258
259
260
261
262
263
264
265
266
267
268
# File 'lib/sugarcube-animations/uiview.rb', line 258

def reframe_to(frame, options={}, more_options={}, &after)
  if options.is_a? Numeric
    options = more_options.merge(duration: options)
  end

  options[:after] = after

  animate(options) do
    self.frame = frame
  end
end

#resize_to(size, options = {}, more_options = {}, &after) ⇒ Object



244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/sugarcube-animations/uiview.rb', line 244

def resize_to(size, options={}, more_options={}, &after)
  if options.is_a? Numeric
    options = more_options.merge(duration: options)
  end

  options[:after] = after

  animate(options) do
    f = self.frame
    f.size = SugarCube::CoreGraphics::Size(size)
    self.frame = f
  end
end

#rotate(options = {}, more_options = {}, &after) ⇒ Object

Changes the current rotation by new_angle (rotate rotates to a specific angle)



289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/sugarcube-animations/uiview.rb', line 289

def rotate(options={}, more_options={}, &after)
  if options.is_a? Numeric
    new_angle = options
    options = more_options
  else
    new_angle = options[:angle]
  end

  old_angle = valueForKeyPath('layer.transform.rotation.z')
  options[:angle] = old_angle + new_angle
  rotate_to(options, &after)
end

#rotate_to(options = {}, more_options = {}, &after) ⇒ Object

Changes the current rotation to new_angle (rotate rotates relative to the current rotation)



272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/sugarcube-animations/uiview.rb', line 272

def rotate_to(options={}, more_options={}, &after)
  if options.is_a? Numeric
    new_angle = options
    options = more_options
  else
    new_angle = options[:angle]
  end

  options[:after] = after

  animate(options) do
    self.transform = CGAffineTransformMakeRotation(new_angle)
  end
end

#scale_to(scale, options = {}, more_options = {}, &after) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/sugarcube-animations/uiview.rb', line 186

def scale_to(scale, options={}, more_options={}, &after)
  if options.is_a? Numeric
    options = more_options.merge(duration: options)
  end

  if scale.is_a?(Numeric)
    scale_x = scale_y = scale
  else  # this could be an array, or CGSize; either way we'll use []
    scale_x = scale[0]
    scale_y = scale[1]
  end

  options[:after] = after

  animate(options) {
    radians = Math.atan2(self.transform.b, self.transform.a)
    # radians = self.valueForKeyPath('layer.transform.rotation.z')
    rotation_t = CGAffineTransformMakeRotation(radians)
    scale_t = CGAffineTransformMakeScale(scale_x, scale_y)
    self.transform = CGAffineTransformConcat(rotation_t, scale_t)
  }
end

#setHeight(newHeight) ⇒ Object



180
181
182
183
184
# File 'lib/sugarcube-uikit/uiview.rb', line 180

def setHeight(newHeight)
  newFrame = self.frame
  newFrame.size.height = newHeight
  self.frame = newFrame
end

#setWidth(newWidth) ⇒ Object



190
191
192
193
194
# File 'lib/sugarcube-uikit/uiview.rb', line 190

def setWidth(newWidth)
  newFrame = self.frame
  newFrame.size.width = newWidth
  self.frame = newFrame
end

#setX(newX) ⇒ Object



160
161
162
163
164
# File 'lib/sugarcube-uikit/uiview.rb', line 160

def setX(newX)
  newFrame = self.frame
  newFrame.origin.x = newX
  self.frame = newFrame
end

#setY(newY) ⇒ Object



170
171
172
173
174
# File 'lib/sugarcube-uikit/uiview.rb', line 170

def setY(newY)
  newFrame = self.frame
  newFrame.origin.y = newY
  self.frame = newFrame
end

#shake(options = {}, more_options = {}) ⇒ Object

Vibrates the target. You can trick this thing out to do other effects, like:

Examples:

# wiggle
view.shake(offset: 0.1, repeat: 2, duration: 0.5, keypath: 'transform.rotation')
# slow nodding
view.shake(offset: 20, repeat: 10, duration: 5, keypath: 'transform.translation.y')


372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'lib/sugarcube-animations/uiview.rb', line 372

def shake(options={}, more_options={})
  if options.is_a? Numeric
    duration = options
    options = more_options
  else
    duration = options[:duration] || 0.3
  end

  offset = options[:offset] || 8
  repeat = options[:repeat] || 3
  if repeat == Float::INFINITY
    duration = 0.1
  else
    duration /= repeat
  end
  keypath = options[:keypath] || 'transform.translation.x'
  if keypath == 'transform.rotation'
    value_keypath = 'layer.transform.rotation.z'
  else
    value_keypath = keypath
  end

  if options[:from_current]
    origin = options[:origin] || valueForKeyPath(value_keypath)
  else
    origin = options[:origin] || 0
  end
  left = origin - offset
  right = origin + offset

  animation = CAKeyframeAnimation.animationWithKeyPath(keypath)
  # sometimes, because of conflicts with CATiming (or something to that
  # effect), calling 'duration=' results in a compiler or runtime error.
  animation.send(:'setDuration:', duration)
  animation.repeatCount = repeat
  animation.values = [origin, left, right, origin]
  animation.keyTimes = [0, 0.25, 0.75, 1.0]
  self.layer.addAnimation(animation, forKey:'shake')
  return self
end

#showObject



103
104
105
106
# File 'lib/sugarcube-animations/uiview.rb', line 103

def show
  self.hidden = false
  return self
end

#slide(direction, options = {}, more_options = {}, &after) ⇒ Object



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/sugarcube-animations/uiview.rb', line 302

def slide(direction, options={}, more_options={}, &after)
  if options.is_a? Numeric
    size = options
    options = more_options
  else
    size = options[:size]
  end

  case direction
  when :left
    size ||= self.frame.size.width
    delta_to([-size, 0], options, &after)
  when :right
    size ||= self.frame.size.width
    delta_to([size, 0], options, &after)
  when :up
    size ||= self.frame.size.height
    delta_to([0, -size], options, &after)
  when :down
    size ||= self.frame.size.height
    delta_to([0, size], options, &after)
  else
    raise "Unknown direction #{direction.inspect}"
  end
  return self
end

#slide_from(direction, options = {}, more_options = {}, &after) ⇒ Object

moves the view off screen, then animates it back on screen. The movement off screen happens immediately, so if you provide a delay: option, it will only affect the movement back on screen.



332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/sugarcube-animations/uiview.rb', line 332

def slide_from(direction, options={}, more_options={}, &after)
  if options.is_a? Numeric
    size = options
    options = more_options
  else
    size = options[:size]
  end

  options[:from_current] = false unless options.key?(:from_current)
  window_size = UIApplication.sharedApplication.windows[0].frame.size

  case direction
  when :left
    size ||= window_size.width
    self.center = CGPoint.new(self.center.x - size, self.center.y)
    self.delta_to([size, 0], options, &after)
  when :right
    size ||= window_size.width
    self.center = CGPoint.new(self.center.x + size, self.center.y)
    self.delta_to([-size, 0], options, &after)
  when :top, :up
    size ||= window_size.height
    self.center = CGPoint.new(self.center.x, self.center.y - size)
    self.delta_to([0, size], options, &after)
  when :bottom, :down
    size ||= window_size.height
    self.center = CGPoint.new(self.center.x, self.center.y + size)
    self.delta_to([0, -size], options, &after)
  else
    raise "Unknown direction #{direction.inspect}"
  end
  return self
end

#sugarcube_cleanupObject



12
13
14
# File 'lib/sugarcube/sugarcube_cleanup.rb', line 12

def sugarcube_cleanup
  NSLog("Good news!  The sugarcube_cleanup method is no longer needed.")
end

#to_s(options = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/sugarcube-to_s/uiview.rb', line 3

def to_s(options={})
  if self.respond_to? :stylename and self.stylename
    suffix = ' stylename: ' + self.stylename.inspect
  else
    suffix = ''
  end
  if options[:inner].is_a? Hash
    inner = ''
    options[:inner].each do |key, value|
      inner += ', ' if inner.length > 0
      inner += "#{key}: #{value.inspect}"
    end
  else
    inner = options[:inner]
  end

  "#{self.class.name}(##{self.object_id.to_s(16)}, #{SugarCube::Adjust::format_frame(self.frame)}" +
                      (inner ? ', ' + inner : '') +
                      ')' +
                      (options.fetch(:superview, true) && self.superview ? ", child of #{self.superview.class.name}(##{self.superview.object_id.to_s(16)})" : '') +
                      suffix
end

#tumble(options = {}, more_options = {}, &after) ⇒ Object

Moves the view off screen while slowly rotating it.

Based on https://github.com/warrenm/AHAlertView/blob/master/AHAlertView/AHAlertView.m



422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# File 'lib/sugarcube-animations/uiview.rb', line 422

def tumble(options={}, more_options={}, &after)
  if options.is_a? Numeric
    default_duration = options
    options = more_options
    side = options[:side] || :left
  elsif options.is_a? Symbol
    side = options
    options = more_options
    default_duration = 0.3
  else
    default_duration = 0.3
    side = options[:side] || :left
  end

  case side
    when :left
      angle = -Math::PI/4
    when :right
      angle = Math::PI/4
    else
      raise "Unknown direction #{side.inspect}"
  end

  options[:duration] ||= default_duration
  options[:options] ||= UIViewAnimationOptionCurveEaseIn|UIViewAnimationOptionBeginFromCurrentState
  reset_transform = self.transform
  reset_after = ->(finished) do
    self.transform = reset_transform
  end

  if after
    options[:after] = ->(finished) do
      reset_after.call(finished)

      if after.arity == 0
        after.call
      else
        after.call(finished)
      end
    end
  else
    options[:after] = reset_after
  end

  self.animate(options) do
    window = UIApplication.sharedApplication.windows[0]
    top = self.convertPoint([0, 0], toView:nil).y
    height = window.frame.size.height - top
    offset = CGPoint.new(0, height * 1.5)
    offset = CGPointApplyAffineTransform(offset, self.transform)
    self.transform = CGAffineTransformConcat(self.transform, CGAffineTransformMakeRotation(angle))
    self.center = CGPointMake(self.center.x + offset.x, self.center.y + offset.y)
  end
end

#tumble_in(options = {}, more_options = {}, &after) ⇒ Object

Moves the view on screen while slowly rotating it.

Based on https://github.com/warrenm/AHAlertView/blob/master/AHAlertView/AHAlertView.m



480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# File 'lib/sugarcube-animations/uiview.rb', line 480

def tumble_in(options={}, more_options={}, &after)
  if options.is_a? Numeric
    default_duration = options
    options = more_options
    side = options[:side] || :left
  elsif options.is_a? Symbol
    side = options
    options = more_options
    default_duration = 0.3
  else
    default_duration = 0.3
    side = options[:side] || :left
  end

  case side
    when :left
      angle = -Math::PI/4
    when :right
      angle = Math::PI/4
    else
      raise "Unknown direction #{side.inspect}"
  end

  reset_transform = self.transform
  reset_center = self.center

  options[:duration] ||= default_duration
  options[:options] ||= UIViewAnimationOptionCurveEaseOut
  options[:after] = after

  window = UIApplication.sharedApplication.windows[0]
  top = self.convertPoint([0, 0], toView:nil).y
  height = window.frame.size.height - top
  offset = CGPoint.new(0, height * -1.5)
  offset = CGPointApplyAffineTransform(offset, self.transform)
  self.transform = CGAffineTransformConcat(self.transform, CGAffineTransformMakeRotation(angle))
  self.center = CGPointMake(self.center.x + offset.x, self.center.y + offset.y)

  self.animate(options) do
    self.transform = reset_transform
    self.center = reset_center
  end
end

#uiimage(use_content_size = false) ⇒ Object

Easily take a snapshot of a UIView.

Calling uiimage with no arguments will return the image based on the bounds of the image. In the case of container views (notably UIScrollView and its children) this does not include the entire contents, which is something you probably want.

If you pass a truthy value to this method, it will use the contentSize of the view instead of the bounds, and it will draw all the child views, not just those that are visible in the viewport.

It is guaranteed that true and :all will always have this behavior. In the future, if this argument becomes something that accepts multiple values, those two are sacred.



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/sugarcube-uikit/uiview.rb', line 78

def uiimage(use_content_size=false)
  scale = UIScreen.mainScreen.scale
  if use_content_size
    UIGraphicsBeginImageContextWithOptions(contentSize, false, scale)
    context = UIGraphicsGetCurrentContext()
    self.subviews.each do |subview|
      CGContextSaveGState(context)
      CGContextTranslateCTM(context, subview.frame.origin.x, subview.frame.origin.y)
      subview.layer.renderInContext(context)
      CGContextRestoreGState(context)
    end
    image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
  else
    UIGraphicsBeginImageContextWithOptions(bounds.size, false, scale)
    layer.renderInContext(UIGraphicsGetCurrentContext())
    image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
  end
  return image
end

#unshift(view) ⇒ Object



31
32
33
34
# File 'lib/sugarcube-uikit/uiview.rb', line 31

def unshift(view)
  self.insertSubview(view, atIndex:0)
  return self
end

#widthObject



186
187
188
# File 'lib/sugarcube-uikit/uiview.rb', line 186

def width
  self.frame.size.width
end

#xObject

Easily get and set a UIView's frame properties



156
157
158
# File 'lib/sugarcube-uikit/uiview.rb', line 156

def x
  self.frame.origin.x
end

#yObject



166
167
168
# File 'lib/sugarcube-uikit/uiview.rb', line 166

def y
  self.frame.origin.y
end

#|(filter) ⇒ Object

Applies a filter (to a UIImage representation) or coerces to another format



35
36
37
38
39
40
41
# File 'lib/sugarcube-pipes/pipes.rb', line 35

def |(filter)
 if filter == UIImage
   self.uiimage
 else
   raise "The `|` operator is not supported for the #{filter.is_a?(Class) ? filter.name : filter.class.name} class"
 end
end