2012-06-04 37 views
0

我試圖將手勢連接到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 

修改後的代碼:以下代碼是在主視圖控制器。我已經從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];  
    } 
} 

SOLUTION:據我瞭解, 自我= [超級初始化] 需要更改爲包含一個CGRECT,該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 
+0

你不是在任何地方設置形狀的框架! – Moxy

回答

2

你應該手勢識別的目標設定爲self,不看,因爲您實現在Shape類的handlerTap:方法。

+0

我試着改變下面每一行的目標,然後在一起,但手勢仍然不起作用。 \t [tap addTarget:self action:@selector(handlerTap :)]; \t [self addGestureRecognizer:tap]; – SimonRH

+0

不,您需要將手勢識別器添加到視圖並將目標設置爲自己。 – DrummerB

+0

我編輯了我的代碼來完成我認爲你告訴我的內容,但它不起作用。 – SimonRH

相關問題