Handles are the small white and black objects that you see when you select a Figure (see next figure). They allow you to manipulate the figure by moving them around. In this tutorial, we will show you how to configure a Handle to alter the size of a Figure. We will as a base the diagram editor we were building in the previous part of the tutorial.
Configuring a Handle is quite simple, basically in the initialization method of your Figure, you have to add the Handle to the handles collection it’s inherited from the Figure class. Let’s modify our SimpleRectangleFigure figure:
In this case we have added 4 handles that will look to the topLeft, topRight, bottomLeft and bottomRight properties of the Figure. If we reload the editor you can see that the Figure has the 4 handles and that if you move them around the SimpleRectangleFigure resizes itself.
Understanding how handles work
When we instantiate a Handle we pass the Figure which the Handle has to observe and a selector as a String. The Handle registers itself as an observer of the Figure so that when:
- The Figure the Handle observes is moved
It moves to a new position that is computed by sending the message to the Figure. In our first case Figure>>topLeft will be evaluated and a Point will be return. That point is used to set the new Frame of the Handle.
- The Handle is moved
The Handle sends Figure>>topLeft: aPoint to the observing Figure so that the Figure updates its Frame. One thing we have to recall is how we implement the - (void) drawRect:(CGRect) rect on: (id) context of our SimpleRectangleFigure:
Because we used the bounds of the SimpleRectangleFigure to draw, we are safe that the Handle will work when we move it around.
In the next episode we will show you how to create a more advance Handle to change the color of the Figure based on the distance to its center!