0

抱歉标题不好:(

我有一个控制器,它有一个滚动视图,我在其中显示一些其他视图,在本例中是一个成分图像,它是 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)))];
}

问题是只有第一个视图处理触摸事件,我不知道为什么:(

你能帮助我吗?

谢谢

4

1 回答 1

4

你打电话时

CGPoint location = [[touches anyObject] locationInView:self];

您正在设置相对于 imageView 边界的位置。但是在你的 if 语句中,

if (CGRectContainsPoint([self frame], location))

您在询问该位置是否在您的框架内。但是框架和边界是不同的。Frame 给出相对于您的超级视图的坐标;bounds 相对于视图本身给出它。

要解决此问题,请将 if 语句更改为

if (CGRectContainsPoint([self bounds], location))

现在您在两个调用中始终使用相同的坐标系,您的问题应该会消失。

于 2010-10-28T17:48:19.270 回答