【发布时间】: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