2

我的代码中有以下 IBAction 方法。

-(IBAction)handleSingleTap:(id)sender
{
    // need to recognize the called object from here (sender)
}


UIView *viewRow = [[UIView alloc] initWithFrame:CGRectMake(20, y, 270, 60)];
// Add action event to viewRow
UITapGestureRecognizer *singleFingerTap = 
[[UITapGestureRecognizer alloc] initWithTarget:self 
                                        action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleFingerTap];
[singleFingerTap release];
//
UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(5,30, 100, 20)];
infoLabel.text = @"AAAANNNNVVVVVVGGGGGG";
//[viewRow addSubview:infoLabel];
viewRow.backgroundColor = [UIColor whiteColor];

// display the seperator line 
UILabel *seperatorLablel = [[UILabel alloc] initWithFrame:CGRectMake(0,45, 270, 20)];
seperatorLablel.text = @" ___________________________";
[viewRow addSubview:seperatorLablel];
[scrollview addSubview:viewRow];

如何调用 IBAction 方法,同时允许它接收该方法的调用者对象?

4

3 回答 3

3

方法签名对于手势识别器和 UIControls 是通用的。两者都将在没有警告或错误的情况下工作。要确定发件人,首先要确定类型...

- (IBAction)handleSingleTap:(id)sender
{
// need to recognize the called object from here (sender)
    if ([sender isKindOfClass:[UIGestureRecognizer self]]) {
        // it's a gesture recognizer.  we can cast it and use it like this
        UITapGestureRecognizer *tapGR = (UITapGestureRecognizer *)sender;
        NSLog(@"the sending view is %@", tapGR.view);
    } else if ([sender isKindOfClass:[UIButton self]]) {
        // it's a button
        UIButton *button = (UIButton *)sender;
        button.selected = YES;
    }
    // and so on ...
}

要调用它,直接调用它,让它连接的 UIControl 调用它,或者让手势识别器调用它。他们都会工作。

于 2012-09-18T05:16:04.227 回答
1

您不必调用它,因为您使用与 一样的方法SelectorUITapGestureRecognizer因此当点击应用程序时它会自动调用。另外,如果你能认出 中方法名后面的冒号action:@selector(handleSingleTap:),则表示向UITapGestureRecognizer方法发送了一个类型的对象。如果您不想发送任何对象,您只需(id)sender从方法中删除冒号和 。

于 2012-09-18T05:14:47.940 回答
1

如你所愿:

[self handleSingleTap:self.view];

sender可以随心所欲,它的id类型。您还可以发送带有标签的 UIButton 实例。

于 2012-09-18T05:15:08.470 回答