gpt4 book ai didi

ios - 从 UIView 属性获取对 NSObject parent 的引用

转载 作者:行者123 更新时间:2023-11-29 03:00:27 25 4
gpt4 key购买 nike

我有一个 (NSObject) Block *my_block ,其属性为 UIView *main_view 。在 ViewController 上,我将 UIPanGestureRecognizer 添加到 main_view,因此手势方法必须在 ViewController 上。是否已经有一种方法可以通过手势方法了解特定 main_viewmy_block 所有者?

这是因为我有一个BlockNSMutableArrayBlocks 在运行时添加到 NSMutableArray 中。

我的第一个想法是通过 NSMutableArray 循环,将每个 main_view 与识别器的 UIView 进行比较。另一个想法是子类化 UIView 并创建对其各自 Block 的引用。但也许有一种更干净的方法来做到这一点。

这是我的类和方法的一个简单示例。

block .h

#import <Foundation/Foundation.h>

@interface Block : NSObject

@property (nonatomic, strong) UIView *main_view;

@end

ViewController.m

#import "ViewController.h"
#import "Block.h"

@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];
[[my_block main_view] addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)]];
[self.view addSubview:[my_block main_view]];
}

- (void)handlePan:(UIPanGestureRecognizer *)recognizer
{
Block *block_temp = [recognizer.view ....];
//recognizer.view = main_view, how to get the Block owner of this view?
}

最佳答案

Block 类是否已成为手势识别器的目标:

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

关于ios - 从 UIView 属性获取对 NSObject parent 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23375126/

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