代码之家  ›  专栏  ›  技术社区  ›  patrick genkilabs

带有touchesend的自定义UIImageVIew仅适用于第一个视图

  •  0
  • patrick genkilabs  · 技术社区  · 14 年前

    对不起,标题不好:(

    我有一个控制器,它有一个滚动视图,在这里我显示一些其他视图,在本例中是一个ingredentimage,它是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
    

    还有一个代码将视图放在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 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)))];
    }
    

    你能帮助我吗?

    谢谢

    1 回复  |  直到 14 年前
        1
  •  4
  •   William Jockusch    14 年前

    当你打电话

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

    您正在根据imageView的边界设置位置。但在你的if陈述中,

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

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

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

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