IOS:向@selector添加一个参数

时间:2011-11-22 15:33:51

标签: ios xcode parameters

当我有这行代码时

UILongPressGestureRecognizer *downwardGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(dragGestureChanged:)];

和这个

- (void)dragGestureChanged:(UILongPressGestureRecognizer*)gesture{
...
}

我想在“@selector(dragGestureChanged :)”中添加一个参数,即“(UIScrollView *)scrollView”,我该怎么办?

2 个答案:

答案 0 :(得分:9)

你不能直接 - UIGestureRecognizer知道如何调用只接受一个参数的选择器。为了完全一般,你可能希望能够传递一个块。 Apple没有构建它,但它很容易添加,至​​少如果你愿意将手势识别器子类化,你想要解决添加新属性和清理后的问题它正确而无需深入研究运行时。

所以,例如(我去的时候写的,未经检查)

typedef void (^ recogniserBlock)(UIGestureRecognizer *recogniser);

@interface UILongPressGestureRecognizerWithBlock : UILongPressGestureRecognizer

@property (nonatomic, copy) recogniserBlock block;
- (id)initWithBlock:(recogniserBlock)block;

@end

@implementation UILongPressGestureRecognizerWithBlock
@synthesize block;

- (id)initWithBlock:(recogniserBlock)aBlock
{
    self = [super initWithTarget:self action:@selector(dispatchBlock:)];

    if(self)
    {
         self.block = aBlock;
    }

    return self;
}

- (void)dispatchBlock:(UIGestureRecognizer *)recogniser
{
    block(recogniser);
}

- (void)dealloc
{
    self.block = nil;
    [super dealloc];
}

@end

然后你可以这样做:

UILongPressGestureRecognizer = [[UILongPressGestureRecognizerWithBlock alloc] 
        initWithBlock:^(UIGestureRecognizer *recogniser)
        {
            [someObject relevantSelectorWithRecogniser:recogniser 
                      scrollView:relevantScrollView];
        }];

答案 1 :(得分:3)

所以方法看起来像这样:

- (void)dragGestureChanged:(UILongPressGestureRecognizer*)gesture
    scrollView:(UIScrollView *)scrollview
{
    ...
}

选择器将如下所示:

UILongPressGestureRecognizer *downwardGesture = [[UILongPressGestureRecognizer alloc]
    initWithTarget:self action:@selector(dragGestureChanged:scrollView:)];