且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

IOS:在@selector中添加一个参数

更新时间:2023-11-30 13:38:10

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

You can't directly — UIGestureRecognizers know how to issue a call to a selector that takes one argument only. To be entirely general you'd probably want to be able to pass in a block. Apple haven't built that in but it's fairly easy to add, at least if you're willing to subclass the gesture recognisers you want to get around the issue of adding a new property and cleaning up after it properly without delving deep into the runtime.

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

So, e.g. (written as I go, unchecked)

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];
        }];