0

我正在尝试将手势连接到 UIView,以便我可以点击对象,但它不起作用。我究竟做错了什么?

形状.h

#import <UIKit/UIKit.h>

@interface Shape : UIView; 

- (id) initWithX: (int)xVal andY: (int)yVal;

@end

形状.m

#import "Shape.h"

@implementation Shape 

- (id) initWithX:(int )xVal andY:(int)yVal {
    self = [super init];    
    UIView *shape = [[UIView alloc] initWithFrame:CGRectMake(xVal, yVal, 10, 10)];
    shape.backgroundColor = [UIColor redColor];
    shape.userInteractionEnabled = YES;     
    [self addSubview:shape];
    return self;
}

@end

修改代码:以下代码在主 ViewController 中。我已经从 Shape 类中删除了 UITapGestureRecognizer。如果我进行以下更改,则代码可以工作,但是响应点击手势的是“框”,而不是“形状”:[shape addGestureRecognizer:tap]; 到 [box addGestureRecognizer:tap];

- (void)handlerTap:(UITapGestureRecognizer *)recognizer {
    //CGPoint location = [recognizer locationInView:[recognizer.view superview]];
    NSLog(@"Success");
}
-(void)drawShapes{
    NSLog(@"Draw");
    if(!box){
        box = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight-100)];
        box.backgroundColor = [UIColor colorWithRed: 0.8 green: 0.8 blue: 0.0 alpha:0.2];
        [self.view addSubview:box];
    }
    for (int i = 0; i<5; i++) {
        int x = arc4random() % screenWidth;
        int y = arc4random() % screenHeight;
        Shape * shape =[[Shape alloc] initWithX:x andY:y ];
        [box addSubview:shape];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        [tap setNumberOfTapsRequired:1];
        [tap addTarget:self action:@selector(handlerTap:)];
        [box addGestureRecognizer:tap];     
    }
}

解决方案:我了解到 self = [super init]; 需要更改以包含一个 CGRECT,该 CGRECT 定义了放置 *shape 的视图的边界。self = [super initWithFrame:CGRectMake(xVal, yVal, 10, 10)];

此外,*shape 需要放置在 0,0 以确保其正确放置在其父级中。UIView *shape = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];

#import "Shape.h"

@implementation Shape 

- (id) initWithX:(int )xVal andY:(int)yVal {
    self = [super initWithFrame:CGRectMake(xVal, yVal, 10, 10)];    
    UIView *shape = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
    shape.backgroundColor = [UIColor redColor];
    shape.userInteractionEnabled = YES;     
    [self addSubview:shape];
    return self;
}
@end
4

1 回答 1

2

您应该将手势识别器的目标设置为self,而不是视图,因为您在类中实现了该handlerTap:方法。Shape

于 2012-06-04T13:28:36.747 回答