gpt4 book ai didi

IOS: 给@selector 添加一个参数

转载 作者:可可西里 更新时间:2023-11-01 03:07:54 25 4
gpt4 key购买 nike

当我有这行代码时

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

还有这个

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

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

最佳答案

您不能直接 — UIGestureRecognizer 知道如何调用只接受一个参数的选择器。为了完全通用,您可能希望能够传入一个 block 。 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];
}];

关于IOS: 给@selector 添加一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8229370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com