Custom UIImageVIew with touchesEnded works only with the first view
Sorry for bad title :(
I've a controller that has a scrollview where I display some other views, in this case an IngredientImage, that is a subclass of uiimageview:
#import "IngredientImage.h"
@implementation IngredientImage
- (id) initWithImage:(UIImage *)image {
if (self = [super initWithImage:image]) {
}
[self setUserInteractionEnabled:YES];
return self;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint location = [[touches anyObject] locationInView:self];
if (CGRectContainsPoint([self frame], location)) {
NSLog(@"This works...");
}
}
- (void)dealloc {
[super dealloc];
}
@end
and there is the code that puts the views in the scrollview
- (void)viewDidLoad {
[super viewDidLoad];
[self addIngredients];
}
- (void)addIngredients {
NSUInteger i;
for (i = 1; i <= 10; i++) {
UIImage *image = [UIImage imageNamed:@"ing.png"];
IngredientImage *imageView = [[IngredientImage alloc] initWithImage:image];
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = imageView.frame;
rect.size.height = 50;
rect.size.width = 50;
imageView.frame = rect;
imageView.tag = i; // tag our images for later use when we 开发者_如何学Cplace them in serial fashion
[ingredientsView addSubview:imageView];
[imageView release];
[image release];
}
UIImageView *view = nil;
NSArray *subviews = [ingredientsView subviews];
// reposition all image subviews in a horizontal serial fashion
CGFloat curYLoc = INGREDIENT_PADDING;
for (view in subviews) {
if ([view isKindOfClass:[IngredientImage class]] && view.tag > 0) {
CGRect frame = view.frame;
frame.origin = CGPointMake(INGREDIENT_PADDING, curYLoc);
view.frame = frame;
curYLoc += (INGREDIENT_PADDING + INGREDIENT_HEIGHT);
}
}
// set the content size so it can be scrollable
[ingredientsView setContentSize:CGSizeMake([ingredientsView bounds].size.width, (10 * (INGREDIENT_PADDING + INGREDIENT_HEIGHT)))];
}
the problem is that only the first view handles the touch event, and I don't know why :(
Can you help me?
Thanks
When you call
CGPoint location = [[touches anyObject] locationInView:self];
you are setting location with respect to the bounds of your imageView. But then in your if statement,
if (CGRectContainsPoint([self frame], location))
you are asking if the location is within your frame. But frame and bounds are different. Frame gives coordinates relative to your superview; bounds gives it relative to the view itself.
To fix this, change your if statement to read
if (CGRectContainsPoint([self bounds], location))
Now you are consistently using the same coordinate system in both calls, and your problem should go away.
精彩评论