为UIImageView实现UITouchDown

8 iphone xcode uiimageview ios4

我知道如何实现touchesBeganUIImageView

是有可能实现UITouchDownUIImageView?(我知道我可以使用touchesBegan,而不是UITouchDown,但我想实现UITouchDown)

Anu*_*rag 13

使用UIButton.

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setImage:someUIImage forState:UIControlStateNormal];
[aButton addTarget:self action:@selector(aMethod) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:aButton];
Run Code Online (Sandbox Code Playgroud)

替代UIButton(更长的方法)

A UIControl实现了用户交互并支持细粒度的用户交互.您可以结合使用a UIImageView和a 的功能UIControl来实现这一点,因为它们都是子类UIView.

要获得此行为,请将UIImageView的对象添加为子视图,以UIControl使图像完全覆盖.然后使用添加事件处理程序到此控件addTarget:action:forControlEvents:.这是一个例子:

// assuming the image view object exists
UIImageView *anImageView = ..;

// create a mask that the covers the image exactly
UIControl *mask = [[UIControl alloc] initWithFrame:anImageView.frame];

// add the image as a subview of this mask
CGSize imageSize = anImageView.frame.size;
anImageView.frame = CGRectMake(0, 0, imageSize.width, imageSize.height);
[mask addSubview:anImageView];

// add a target-action for the desired control events to this mask
[mask addTarget:self action:@selector(someMethod:) forControlEvents:UIControlEventTouchUpInside];

// add the mask as a subview instead of the image
[self.view addSubview:mask];
Run Code Online (Sandbox Code Playgroud)