[英]Custom UIImageVIew with touchesEnded works only with the first view
對不起,標題不好:(
我有一個具有scrollview的控制器,在其中顯示了其他一些視圖,在本例中為IngredientImage,它是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
並且有將視圖放入滾動視圖的代碼
- (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 place 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)))];
}
問題是只有第一個視圖處理觸摸事件,我不知道為什么:(
你能幫助我嗎?
謝謝
你打電話時
CGPoint location = [[touches anyObject] locationInView:self];
您正在相對於imageView的邊界設置位置。 但是然后在您的if語句中
if (CGRectContainsPoint([self frame], location))
您詢問的位置是否在您的框架內。 但是框架和界限是不同的。 框架給出相對於您的超級視圖的坐標; 邊界使它相對於視圖本身。
要解決此問題,請將您的if語句更改為
if (CGRectContainsPoint([self bounds], location))
現在,您在兩個調用中始終使用相同的坐標系,並且您的問題將消失。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.