【问题标题】:Connect a UITapGestureRecognizer to a UIView将 UITapGestureRecognizer 连接到 UIView
【发布时间】:2012-06-04 13:25:56
【问题描述】:

我正在尝试将手势连接到 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。如果我进行以下更改,该代码将起作用,但它是响应点击手势的“框”,而不是“形状”: [形状添加手势识别器:点击]; 到 [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 = [超级初始化]; 需要更改为包含一个 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

【问题讨论】:

  • 你没有在任何地方设置形状的框架!

标签: objective-c ios5 xcode4


【解决方案1】:

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

【讨论】:

  • 我尝试改变下面每一行的目标,然后一起改变,但手势仍然不起作用。 [点击 addTarget:self action:@selector(handlerTap:)]; [self addGestureRecognizer:tap];
  • 不行,你需要将手势识别器添加到视图中,并将目标设置为self。
  • 我编辑了我的代码,按照我认为你告诉我的去做,但它不起作用。
  • 你设置了它的框架吗?您只需调用[super init] 并且不要设置框架。我认为默认是CGRectZero
  • 对不起,我不明白你的意思。为什么我必须设置框架以及在哪里/如何设置?
猜你喜欢
  • 2018-10-07
  • 2012-07-14
  • 2012-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-04
相关资源
最近更新 更多