在initWithTarget调用中使用Selector发送参数

时间:2012-11-24 15:46:40

标签: objective-c syntax arguments selector

我试图将以下代码修改为单个方法。目前,八个相同的方法用于处理八个UIButton实例上的点击。理想情况下,我只想将UIButton作为参数传递给@selector,这样我就可以避免需要八种相同的方法。我正在努力将参数传递给选择器的语法。如果可能的话,我想要一个handleTap: onButton:方法。目前,在按钮1到8上有八种方法(handleTap1handleTap8)执行相同的操作。

UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap1:)];
UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap2:)];
UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap3:)];
UITapGestureRecognizer *tap4 = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap4:)];
UITapGestureRecognizer *tap5 = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap5:)];
UITapGestureRecognizer *tap6 = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap6:)];
UITapGestureRecognizer *tap7 = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap7:)];
UITapGestureRecognizer *tap8 = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap8:)];
[let1Button addGestureRecognizer: tap1];
[let2Button addGestureRecognizer: tap2];
[let3Button addGestureRecognizer: tap3];
[let4Button addGestureRecognizer: tap4];
[let5Button addGestureRecognizer: tap5];
[let6Button addGestureRecognizer: tap6];
[let7Button addGestureRecognizer: tap7];
[let8Button addGestureRecognizer: tap8];

这是其中一个方法的示例,显然我想用传入的参数替换let1Button来表示任何按钮。

- (void) handleTap1: (UITapGestureRecognizer *) recognizer
{
    [_box setText: [_box.text stringByAppendingString: [let1Button titleForState: UIControlStateNormal]]];
    [let1Button setUserInteractionEnabled:NO];
    [let1Button setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];

}

3 个答案:

答案 0 :(得分:4)

UIViewUIButtonUIView的子类)具有属性view。这是手势识别器附加到

的视图
UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap:)];
[let1Button addGestureRecognizer: tap1];

- (void) handleTap: (UITapGestureRecognizer *) recognizer
{
    UIButton *button = (UIButton *)recognizer.view;
    [_box setText: [_box.text stringByAppendingString: [UIButton titleForState: UIControlStateNormal]]];
    [UIButton  setUserInteractionEnabled:NO];
    [UIButton setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];

}

答案 1 :(得分:1)

手势识别器具有属性视图。你可以检查一下,找出手势执行的按钮。

答案 2 :(得分:1)

手势识别器作为参数移交给动作。 在操作方法中,您可以访问该视图。

UIView myView = recognizer.view
if (myView isKindOfClass:[UIButton class])
{
   ...
}