如何以编程方式调用id发送方的IBAction方法?

时间:2012-09-18 05:09:16

标签: ios selector ibaction

我的代码中有以下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方法,同时允许它接收该方法的调用者对象?

3 个答案:

答案 0 :(得分:3)

方法签名对于手势识别器和UIControl来说很常见。两者都可以在没有警告或错误的情要确定发件人,请先确定类型......

- (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调用它,或者让手势识别器调用它。他们都会工作。

答案 1 :(得分:1)

您不必调用它,因为您使用Selector作为UITapGestureRecognizer的方法,因此当点击应用时它会自动调用。 此外,如果您可以在action:@selector(handleSingleTap:)中的方法名称后面识别冒号,则表示向该方法发送类型为UITapGestureRecognizer的对象。如果您不想发送任何对象,只需从方法中删除冒号和(id)sender

答案 2 :(得分:1)

如你所愿:

[self handleSingleTap:self.view];

sender可以随意添加,id类型。您还可以发送带有标记的UIButton实例。