从自定义UIImageView子类通知ViewController

时间:2011-02-03 14:07:15

标签: cocoa-touch ios uiimageview subclass

我想定义一个子类化UIImageView的可拖动图像类,分离它们的外观(在子类上)以及用户界面对它们移动位置的反应(在视图控制器上)

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实现

....
  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!!!");
    }
}

....

我无法弄清楚如何通过touchesEnded(例如)从myType1Image类通知ViewController。 我在viewcontroller上编写了所有代码,但是我想使用子类来完成它,所以我可以将事件处理和图像的可视化与界面的真实功能分开。 因此,如果我有15个可拖动的图像,我不必猜测触摸的是什么图像,并决定要应用的视觉效果。

有可能吗?这是一个错误的方法吗?

1 个答案:

答案 0 :(得分:0)

首先,类名应始终以大写字母(MyType1Image)开头。

创建一个MyType1ImageDelegate协议,在其中声明图像视图发送给其委托(视图控制器)的委托方法。这些方法的第一个参数应始终为MyType1Image *类型(告诉委托消息来自哪个对象)。

您的MyType1Image还需要id <MyType1ImageDelegate> delegate属性。

当视图控制器创建图像视图时,它会将自身设置为图像视图的委托。只要图像视图想要向视图控制器发送消息,您就可以将消息发送给代理。