2012-06-21 34 views
10

Tôi đang sử dụng mã dưới đâyLàm thế nào để vượt qua lập luận để hành động trong UIGestureRecognizer initWithTarget hành động

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(processTap)]; 

- (void) processTap 
{ 
//do something 
} 

Nhưng tôi cần phải gửi một dữ liệu với chức năng processTap. Có anyway để làm điều này?

+0

Tôi nghĩ điều này sẽ giúp bạn hiểu: http: //stackoverflow.com/a/5035335/177136 – Ger

Trả lời

30

Ví dụ:

UIImageView *myPhoto = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"tab-me-plese.png"]]; 
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(processTap:)]; 

[myPhoto setTag:1]; //set tag value 
[myPhoto addGestureRecognizer:tap]; 
[myPhoto setUserInteractionEnabled:YES]; 

- (void)processTap:(UIGestureRecognizer *)sender 
{ 
    NSLog(@"tabbed!!"); 
    NSLog(@"%d", sender.view.tag);  
} 
+4

Chào mừng bạn đến với Stack Overflow! Luôn cố gắng cung cấp giải thích cho mã của bạn. –

+1

Nếu tất cả những gì bạn cần là 'UIView', trong đó cử chỉ xảy ra, thì đây là câu trả lời kém tài liệu, nhưng hợp lệ. Nếu không, bạn phải kết hợp với phản hồi này: http://stackoverflow.com/questions/11594610/objective-c-storing-hidden-information-into-a-uiview từ @nielsbot – SwiftArchitect

+0

Gắn thẻ này cực kỳ hữu ích khi chuyển UserData - không cần phải tính toán vị trí lộn xộn ... – kfmfe04

3

Có một câu trả lời tốt cho một câu hỏi tương tự tại iOS - UITapGestureRecognizer - Selector with Arguments, nhưng nếu bạn muốn để truyền dữ liệu mà bạn không muốn đính kèm vào xem, tôi khuyên bạn nên tạo một giây chức năng có quyền truy cập vào dữ liệu bạn cần. Ví dụ:

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(passDataToProcessTap)]; 

- (void)passDataToProcessTap { 
    [self processTapWithArgument:self.infoToPass]; 
    // Another option is to use a static variable, 
    // Or if it's not dynamic data, you can just hard code it 
} 

- (void) processTapWithArgument:(id)argument { 
    //do something 
} 
Các vấn đề liên quan