views:

1105

answers:

5

I am just getting stated with iPhone development and can't seem to find the answer I am looking for what I want to do.

It seems like I should be able to programmatically create a UIImageView and then set up an event handler for it's touch functions.

in c# i would have something that looks like

Button b = new Button(); b.Click+= my handler code

right now I have this

CGRect myImageRect = CGRectMake(0.0f, 0.0f, 141.0f, 151.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];

myImage.userInteractionEnabled = YES;
[myImage setImage:[UIImage imageNamed:@"myImage.png"]];
myImage.opaque = YES; // explicitly opaque for performance
[self.view addSubview:myImage];
[myImage release];

What do I need to do to override the touch events?

thanks

A: 

I've not found a way to do it directly with UIImageView. But if you subclass it and override the nextResponder method to return a delegate under your control you can do what you're after. Expose the delegate as a property of the subclass and then you can pass in a delegate for the touch events and change it at any time.

Phil Nash
A: 

I've seen other answers suggest putting an invisible button underneath the UIImageView, setting the image view to userInteractionEnabled: NO, and letting the touches pass through to the button.

Kirk van Gorkom
+2  A: 

While it is not the complete answer to your question, i think the following solution might be better then doing the "invisible-button-workaround".. simply subclass from UIImageView and override the following method:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

 //your UIImageView has been touched :)

 //event -> "A UIEvent object representing the event to which the touches belong."

 //touches -> "A set of UITouch instances in the event represented by event that    represent the touches in the UITouchPhaseEnded phase."

}

hope this helps...

samsam
Really this is not the answer I was looking for. But it seems that the only way I can find is to use inheritance. I guess c# has spoiled me to the point where I think methods like this should be available without that much work. However, thanks.
madmik3
A: 

I did what this guy said (click here) and it worked a treat.

Mike Howard
A: 

Just use a custom UIButton with the image as background image.

Daniel Joseph Claudin