Я пытаюсь подключить жест к UIView, чтобы я мог использовать объект, но он не работает. Что я делаю не так?Подключить UITapGestureRecognizer к UIView
Shape.h
#import <UIKit/UIKit.h>
@interface Shape : UIView;
- (id) initWithX: (int)xVal andY: (int)yVal;
@end
Shape.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
MODIFIED КОД: Следующий код находится в главном ViewController. Я удалил UITapGestureRecognizer из класса Shape. Код работает, если я делаю следующее изменение, но тогда это «поле», которое реагирует на жест tap, а не «shape»: [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];
}
}
РЕШЕНИЕ: Я узнал, что само = [супер INIT]; необходимо изменить, чтобы включить CGRECT, который определяет границы вида, в которые * форма помещается. self = [super initWithFrame: CGRectMake (xVal, yVal, 10, 10)];
Кроме того, * форма должна быть размещена на 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
вы нигде не устанавливаете рамку формы! – Moxy