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

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

还有这个

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

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

解决方法

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

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

  1. typedef void (^ recogniserBlock)(UIGestureRecognizer *recogniser);
  2.  
  3. @interface UILongPressGestureRecognizerWithBlock : UILongPressGestureRecognizer
  4.  
  5. @property (nonatomic,copy) recogniserBlock block;
  6. - (id)initWithBlock:(recogniserBlock)block;
  7.  
  8. @end
  9.  
  10. @implementation UILongPressGestureRecognizerWithBlock
  11. @synthesize block;
  12.  
  13. - (id)initWithBlock:(recogniserBlock)aBlock
  14. {
  15. self = [super initWithTarget:self action:@selector(dispatchBlock:)];
  16.  
  17. if(self)
  18. {
  19. self.block = aBlock;
  20. }
  21.  
  22. return self;
  23. }
  24.  
  25. - (void)dispatchBlock:(UIGestureRecognizer *)recogniser
  26. {
  27. block(recogniser);
  28. }
  29.  
  30. - (void)dealloc
  31. {
  32. self.block = nil;
  33. [super dealloc];
  34. }
  35.  
  36. @end

然后你就可以这样做:

  1. UILongPressGestureRecognizer = [[UILongPressGestureRecognizerWithBlock alloc]
  2. initWithBlock:^(UIGestureRecognizer *recogniser)
  3. {
  4. [someObject relevantSelectorWithRecogniser:recogniser
  5. scrollView:relevantScrollView];
  6. }];

猜你在找的iOS相关文章