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

前端之家收集整理的这篇文章主要介绍了IOS:在@selector中添加一个参数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我有这行代码
UILongPressGestureRecognizer *downwardGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(dragGestureChanged:)];

还有这个

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

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

解决方法

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

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

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];
        }];
原文链接:https://www.f2er.com/iOS/334836.html

猜你在找的iOS相关文章