I want to define a class of draggable images subclassing UIImageView, separating how they look (on the subclass) and what the user interface react to where they move (on the viewcontroller)
myType1Image.h
@interface myType1Image : UIImageView { }
myType1Image.m
...
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
// Retrieve the initial touch point
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
// Move relative to the original touch point with some special effect
}
- (void) touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
// Notify the ViewController ... here is my problem...how?
// would call GotIt on viewController for example
}
...
viewcontroller implementation
....
myType1Image *img = [[myType1Image alloc] initWithImage:[UIImage imageNamed:@"iOSDevTips.png"]];
img.center = CGPointMake(110, 75);
img.userInteractionEnabled = YES;
[subview addSubview:img];
...
- (void) gotIt:(id) (myType1Image *)sender{
if (CGRectContainsPoint( myimage.frame, [sender.center] )){
NSLog(@"Got IT!!!");
}
}
....
I can’t figure out how ViewController could be notified from the myType1Image class, for touchesEnded (for example).
I did it writing all code on the viewcontroller, but I want to do it using subclasses so I can separate the event handling and the visualization of the images from the real funcionality of my interface.
So if I have 15 draggable images, I haven’t to guess what image is touching, and deciding the visual effects to apply.
Is it possible? Is an erroneus aproach?
First, class names should always begin with a capital letter (
MyType1Image).Create a
MyType1ImageDelegateprotocol in which you declare delegate methods that the image view sends to its delegate (the view controller). The first argument of these methods should always be of the typeMyType1Image *(to tell the delegate from which object the message comes).Your
MyType1Imagealso needs aid <MyType1ImageDelegate> delegateproperty.When your view controller creates an image view, it sets itself as the image view’s delegate. Whenever the image view wants to send a message to the view controller, you have it send the message to the delegate.