PDA

View Full Version : UITouch not working for UIImageView




lamfan
Aug 4, 2008, 04:52 AM
Here is the source code, including 4 files

inside the UIView instand touchesBegan method

NSLog(@"touch"); <---working
if([touch view] == view1)
{
NSLog(@"moving"); <---not working don't know why?
}

1.ShootingGameAppDelegate.h
2.ShootingGameAppDelegate.m
3.MainView.h
4.MainView.m


ShootingGameAppDelegate.h
#import <UIKit/UIKit.h>

@class MainView;

@interface ShootingGameAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
MainView *mainView;
}

@property (nonatomic, retain) UIWindow *window;
@property (nonatomic, retain) MainView *mainView;

@end

ShootingGameAppDelegate.m
#import "ShootingGameAppDelegate.h"
#import "MainView.h"

@implementation ShootingGameAppDelegate

@synthesize window, mainView;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
mainView = [[MainView alloc] initWithFrame:[window bounds]];
[window addSubview:mainView];
// Override point for customization after app launch
[window makeKeyAndVisible];
}


- (void)dealloc {
[window release];
[super dealloc];
}


@end

MainView.h
#import <UIKit/UIKit.h>


@interface MainView : UIView {
UIImageView *view1;
}

@property (nonatomic, retain)UIImageView *view1;

@end


MainView.m

#import "MainView.h"

@implementation MainView

@synthesize view1;

- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100.0, 100.0, 57.0, 57.0)];
imageView.image = [UIImage imageNamed:@"Icon.png"];
imageView.center = self.center;
self.view1 = imageView;
[imageView release];
[self addSubview:view1];
}
return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touch");

UITouch *touch = [[event allTouches] anyObject];
if([touch view] == view1)
{
NSLog(@"moving");
CGPoint location = [touch locationInView:self];
view1.center = location;
}
}

- (void)dealloc {
[super dealloc];
}

@end



lawicko
Aug 4, 2008, 05:24 AM
I found this in documentation:
New image view objects are configured to disregard user events by default. If you want to handle events in a custom subclass of UIImageView, you must explicitly change the value of the userInteractionEnabled property to YES after initializing the object.

lamfan
Aug 4, 2008, 06:00 AM
thanks that's working now! cool!