views:

1888

answers:

2

Simply, I have placed an image with the Interface Builder in a UIView. Now I want to run a method/function when I am touching that image, for example when another image should be loaded.

My Code:

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

   // UITouch *touch = [touch anyObject];
  bild_1_1.image = [UIImage imageNamed:@"t_1_4.jpg"];

  //}
}
+1  A: 

What you want could be easily done by placing UIButton instead of UIImage and changing its background image using method setBackgroundImage:forState: at TouchUpInside event handler.

Yuriy Zhyromskiy
Thank for the 1st answer! But a button is not well working for my planned steps.
Markus S.
A: 

You need handle touch event from you UIView. To do it you should create subclass of UIView and add your realisation of touchesBegan:withEvent: method, here simplest example:

//  TouchSimpleView.h
@interface TouchSimpleView : UIImageView {
    id  delegate;
}
@property(retain) id delegate;
@end

@interface NSObject(TouchSimpleView)
-(void)didTouchView:(UIView *)aView;
@end 

//  TouchSimpleView.m
#import "TouchSimpleView.h"
@implementation TouchSimpleView
@synthesize delegate;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"touchesBegan!!! ");
    if ( delegate != nil && [delegate respondsToSelector:@selector(didTouchView:)] ) {
        [delegate didTouchView:self];
    } 
    [super touchesBegan:touches withEvent:event];
}
@end

Then you can use views of this class when you want to handle touches, for example:

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    [window makeKeyAndVisible];
    touchView = [[TouchSimpleView alloc] initWithFrame:CGRectMake(50, 50, 200, 300)];
    touchView.delegate = self;
    [window addSubview:touchView];

    imageView =[[UIImageView alloc] initWithFrame:touchView.frame];
    imageView.image = [UIImage imageNamed:@"image1.png"];
    [touchView addSubview:imageView];
}

-(void)didTouchView:(UIView *)aView{
    NSLog(@"view touched, changing image");
    imageView.image = [UIImage imageNamed:@"image2.png"];
}
Vladimir
Do I have to declare touchView or do I have to paste all but [window...]; in the (void)applicationDidFin.... function?
Markus S.
In the piece of code above it is supposed touchView and imageView was declared in h file://MyAppDelegate.h@interface MyAppDelegate : NSObject <UIApplicationDelegate> {UIWindow *window;UIImageView *imageView;TouchSimpleView *touchView;//...Note that you can use TouchSimpleView objects anywere, not only in app delegate. Note also that you can create other delegate methods, for example send also touch cordinates, or handle not only touchesBegan... but also touchesMoved or touchesCanceled events.
Vladimir