Concerning an event handler for UIImageView

I just declare the development of the iPhone and it seems I can’t find the answer I'm looking for, what I want to do.

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

in c # i will have something similar to

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

right now i have it

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 touch events?

thank

+5
source share
7 answers

, , , " - ". UIImageView :

-(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."

}

, ...

+9

mainview "about", . (mainview) touchBegan. , , "", . UIImageView "aboutImg", (.. β†’ ).

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if ([touch view] == aboutImg){
        [self ShowAbout];
    }
}

, " ".

+5

UIButton .

+3

UIImageView. nextResponder, , , . , .

0

, UIImageView, userInteractionEnabled: NO .

0

You do not need to have anything to do with UIImageView, you can use UIButton with type custom and add an internal action to it ... set button.imageview setImage: i-e:

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0,0,100,100); //edit for you own frame
UIImage *img = [UIImage imageNamed:@"myimage.png"];
[button setImage:img forState:UIControlStateNormal];

If you want to go with UIImageView, you need to add gestures to your image. otherwise you can subclass your UIImageView and then use touch events.

0
source

The easiest way to add an onClick event to a UIImageView or to a UIView is to add a gesture recognition flag to it.

UIImage *myImage = [UIImage imageNamed:@"myImage.png"];
UIImageView *myImageView = [[UIImageView alloc] initWithImage: myImage];

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action: @selector(onImageViewClicked)];
singleTap.numberOfTapsRequired = 1;
singleTap.numberOfTouchesRequired = 1;
[self.myImageView addGestureRecognizer:singleTap];
[self.myImageView setUserInteractionEnabled:YES];
0
source