我有(NSObject) Block *my_block
作为属性UIView *main_view
。在ViewController上我向UIPanGestureRecognizer
添加main_view
,因此手势方法必须在ViewController上。是否已经有办法从手势方法中了解特定my_block
的{{1}}所有者?
这是因为我有main_view
NSMutableArray
。 Block
会在运行时添加到Blocks
。
我的第一个想法是通过NSMutableArray
循环比较识别器的每个NSMutableArray
和main_view
。另一个想法是继承UIView
并创建对其各自UIView
的引用。但也许有一种更清洁的方法。
这是我的类和方法的一个简单示例。
Block
#import <Foundation/Foundation.h>
@interface Block : NSObject
@property (nonatomic, strong) UIView *main_view;
@end
答案 0 :(得分:1)
您的Block
课程是否为您的手势识别器的target
:
<强> Block.h 强>
@interface Block : NSObject
@property (nonatomic, strong) UIView *main_view;
@end
<强> Block.m 强>
@implementation Block
-(void)handleMainViewPan:(UIPanGestureRecognizer *)recognizer
{
// Now recognizer.view is the same view as self.main_view
// Use self as this is now your block
}
@end
<强> ViewController.m 强>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// the Blocks are actually added on runtime to a NSMutableArray, but this is a simpler example
Block *my_block = [[Block alloc] init];
UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:my_block action:@selector(handleMainViewPan:)];
[my_block.main_view addGestureRecognizer:gestureRecognizer];
[self.view addSubview:my_block.main_view];
}
@end
答案 1 :(得分:0)
您也可以使用函数来代替子类化UIView:
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
id objc_getAssociatedObject(id object, const void *key)
来自docs
使用给定的键和设置给定对象的关联值 协会政策。
答案 2 :(得分:0)
如果您已在数组中包含块(我相信该数组是ViewController
中的属性),您可以找到loop
的一个块。
示例:
// self.blocks is NSMutableArray where blocks are stored
- (void)handlePan:(UIPanGestureRecognizer *)recognizer
{
Block *owner = nil;
for (block in self.blocks) {
if (block.main_view == recognizer.view) {
owner = block;
break;
}
}
}