2015-11-08 62 views
0

在下面的代碼中,我定義了一個函數來創建箭頭(如圖像)並將這些箭頭添加到視圖中。但是,我收到了一條警告,說Undeclared selector 'method'。有人可以建議另一種方法來避免這種警告將字符串參數傳遞給UITapGestureRecognizer動作

-(void)createArrow:(NSString*)direction View:(UIView*)view 
{ 
    int x,y; 
    NSString *img; 
    NSString *method; 

    if ([direction isEqualToString:@"up"]){ 
     x = 55; 
     y = 6; 
     _arrow = _arrowUp; 
     method = @"upTap"; 
     img = @"up-arrow.png"; 
    }else if ([direction isEqualToString:@"down"]){ 
     x = 55; 
     y = 70; 
     _arrow = _arrowDown; 
     method = @"downTap"; 
     img = @"down-arrow.png"; 
    }else if ([direction isEqualToString:@"left"]){ 
     x = 22; 
     y = 39; 
     _arrow = _arrowLeft; 
     method = @"leftTap"; 
     img = @"left-arrow.png"; 
    }else if ([direction isEqualToString:@"right"]){ 
     x = 90; 
     y = 39; 
     _arrow = _arrowRight; 
     method = @"rightTap"; 
     img = @"right-arrow.png"; 
    } 

    _arrow = [[UIImageView alloc] initWithFrame: CGRectMake(x, y, 27, 27)]; 
    [_arrow setImage:[UIImage imageNamed:img]]; 
    UITapGestureRecognizer *gest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(method)]; 
    [_arrow setUserInteractionEnabled:YES]; 
    [_arrow addGestureRecognizer:gest]; 
    [view addSubview:_arrow]; 
} 

回答

1

Avi是正確的。但更簡單的是,爲什麼不只是製作類型的method,並且在每種情況下都將其直接設置爲要觸發的選擇器,然後將選擇器傳遞給手勢識別器?例如:

int x,y; 
NSString *img; 
SEL method; 

if ([direction isEqualToString:@"up"]){ 
    ... 
    method = @selector(upTap); 
    ... 
} else if ([direction isEqualToString:@"down"]){ 
    ... 
    method = @selector(downTap); 
    ... 
} else if ([direction isEqualToString:@"left"]){ 
    ... 
    method = @selector(leftTap); 
    ... 
} else if ([direction isEqualToString:@"right"]){ 
    ... 
    method = @selector(rightTap); 
    ... 
} 

... 
UITapGestureRecognizer *gest = [[UITapGestureRecognizer alloc] initWithTarget:self action:method]; 
... 
1

選擇器名稱是C字符串,而不是NSStrings。請將method更改爲char *,並刪除前導@或使用NSSelectorFromString(method)

另一種選擇是聲明method作爲SEL類型,並將其直接分配給您的if語句的每個塊。

相關問題