gpt4 book ai didi

ios - 将 UIGestureRecognizer 附加到封装的 UIViews

转载 作者:行者123 更新时间:2023-11-29 03:56:55 24 4
gpt4 key购买 nike

我对 UITapGestureRecognizer 有一个奇怪的问题,当调用它的操作时,我总是会遇到崩溃或抛出异常(无法识别的选择器)。我以前使用过手势识别器,但这次我将其附加到 UIView ,它是 NSObject 的属性(并且我使用该对象的方法来构造 View )。以下是我正在做的事情的一个最小示例:

MyObject.h:

#import <Foundation/Foundation.h>
@interface MyObject : NSObject
@property (nonatomic, strong) UIView *aView;
- (void)createViewWithFrame:(CGRect)frame;
@end

MyObject.m:

@interface MyObject ()
- (void)tapped:(id)sender; // Non-specific id type for brevity
@end

@implementation MyObject

- (void)tapped:(id)sender {
NSLog(@"Tapped");
}

- (void)createViewWithFrame:(CGRect)frame {

_aView = [[UIView alloc] initWithFrame:frame];
self.aView.backgroundColor = [UIColor blueColor];
self.aView.userInteractionEnabled = YES;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(tapped:)];

[self.aView addGestureRecognizer:tap];

}

ViewController.m:

- (void)viewDidAppear:(BOOL)animated {

[super viewDidAppear:animated];

MyObject *obj = [[MyObject alloc] init];
[obj createViewWithFrame:self.view.frame]; // Excuse poor frame - example only

[self.view addSubview:obj.aView];
}

然后,当我点击 View 时,应用程序在此处崩溃:

libobjc.A.dylib`objc_msgSend:
0x10e008c: movl 8(%esp), %ecx
0x10e0090: movl 4(%esp), %eax
0x10e0094: testl %eax, %eax
0x10e0096: je 0x10e00e8 ; objc_msgSend + 92
0x10e0098: movl (%eax), %edx
0x10e009a: pushl %edi
0x10e009b: movl 8(%edx), %edi ; Thread 1: EXC_BAD_ACCESS (code=2, address=0x9)
0x10e009e: pushl %esi
0x10e009f: movl (%edi), %esi
0x10e00a1: movl %ecx, %edx

确切的崩溃点各不相同,我偶尔会收到无效选择器错误。 NSLog 自然不会发生。我之前(成功)使用过手势识别器,这让我相信问题出在我的设置/设计中。谁能解释为什么手势识别器在这种情况下无法正常工作?

最佳答案

问题出在 MyObject 的范围上,全局声明变量,

@property(nonatomic, strong) MyObject *obj;

在您的 viewDidAppear 中,初始化并添加 View

self.obj = [[MyObject alloc] init];
[self.obj createViewWithFrame:self.view.frame];
[self.view addSubview:self.obj.aView];

就是这样。

现在可以运行了!!

问题是什么?,*MyObject obj 的范围以 viewDidAppear 方法结束。当识别到点击时,它正在寻找对象来触发给定的方法。但该对象不存在。

关于ios - 将 UIGestureRecognizer 附加到封装的 UIViews,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16380905/

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