如何在@selector(目标c)中传递变量?

时间:2014-11-07 11:51:10

标签: ios objective-c selector

如果我有

UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(somefunction:)];

-(void)somefunction :(id) sender{}

将变量传递给某个函数的正确语法是什么?我试过了(但它不起作用)

UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(somefunction: somensstring:)];

-(void)somefunction: (NSString *) somestuff :(id) sender{}

2 个答案:

答案 0 :(得分:2)

//添加点按手势

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

//在TableView中获取TouchLocation

-(void)HandleTap:(UITapGestureRecognizer*)tap
{
    CGPoint point = [tap locationInView:theTableView];

    NSIndexPath *theIndexPath = [theTableView indexPathForRowAtPoint:point];
}

你可以根据tableView From Array的indexPath获得你想要的任何信息;

答案 1 :(得分:1)

您应该以这种方式定义somefunction方法,

-(void)somefunction:(UIGestureRecognizer *) sender {};

简单方法

-(void)somefunction:(UIGestureRecognizer *) sender {
    UIView *view = (UIView *)sender.view; 
    //1.here you can take any view, UILabel, UIImageView or anything on which you've 
    //added tap gesture

    //2.now, distinguish view by tag
    if(view.tag == someTag1) {
        //create a NSString to use when tap
    }
    else if(view.tag == someTag2) {
        //do something else
    }
};

让它变得有点复杂

  • 定义相同的方法(如上所述) 但是您从识别器中获取的视图,使其成为子类。
  • 例如如果您在UILabel上设置了点按手势,则创建UILabel的子类,然后在其上添加手势。
  • 还要为该子类添加所需的属性。
  • 在向其添加手势时,还要为其设置变量(或任何内容)。
  • 当用户点击时,它仍可供您使用。

这里是UILabel子类的例子,

@interface MyCustomLabel : UILabel 
@property (nonatomic, strong) NSString *someString;
@end;

现在您可以使用此自定义标签,

#import "MyCustomLabel.h"

MyCustomLable *lbl = [[MyCustomLable alloc] init];
lbl.frame = CGRectMake(0,0,200,50);
//add gesture on label
lbl.someString = @"Some text";
[self.view addSubview:lbl];

现在上面的方法几乎没有变化,

-(void)somefunction:(UIGestureRecognizer *) sender {
    MyCustomLabel *lbl = (MyCustomLabel *)sender.view; 
    NSLog(@"My String %@",lbl.someString);
};