제스처를 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
수정 된 코드 : 다음 코드는 메인의 ViewController에 있습니다. Shape 클래스에서 UITapGestureRecognizer를 제거했습니다. 다음 코드를 변경하면 코드가 작동하지만 '모양'이 아닌 탭 제스처에 응답하는 '상자'입니다. [shape addGestureRecognizer : tap]; ~ [상자 addGestureRecognizer : 탭];
- (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];
}
}
해결책 : 내가 배운 그 자기 = [슈퍼 초기화] 은 * 모양이 배치 된 뷰의 경계를 정의하는 CGRECT를 포함하도록 변경해야합니다. self = [super initWithFrame : CGRectMake (xVal, yVal, 10, 10)];
또한 * 모양은 부모 내에서 올바른 위치에 배치되도록 0,0에 배치해야합니다. UIView * shape = [[UIView alloc] initWithFrame : CGRectMake (0, 0, 10, 10)]; 당신이 Shape
클래스의 handlerTap:
방법을 구현하기 때문에
#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