前提是我已经阅读了所有类似的 S.O.线程,我还没有找到适合我的解决方案。
我有一个带有按钮的 imageView Controller ,并且工作正常。
UIImage* image = [UIImage imageNamed:@"background"];
[self.imageView setImage:image];
然后我添加“A”,从 NSObject 派生的接口(interface),带有 UIImageView 和“B”数组:
A* a = [[A alloc] initWithImageView:self.imageView];
[A loadButtons];
啊
@interface A : NSObject
@property (nonatomic, strong) UIImageView* imageView;
- (void)loadButton;
@end
上午
- (id)initWithImageView:(UIImageView*)imageView {
self = [super init];
self.myArray = [[NSMutableArray alloc] init];
self.imageView = imageView;
return self;
}
- (void)loadButton {
B* b = [[B alloc] init];
[self.myArray addObject:b];
[self.imageView addSubview:b.button];
}
B.h
@interface B : NSObject
@property (nonatomic, strong) UIButton* button;
@end
米
- (id)init {
self = [super init];
self.button = [[UIButton alloc] init];
self.button.frame = CGRectMake(0, 0, 20, 20);
[self.button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
return self;
}
- (void)buttonClicked:(id)sender {
...
}
现在的问题是,当用户单击按钮时,应用程序崩溃在控制台上报告没有错误,但在 main 上移动:
0x10ab52900 <+1282>: movq 0xb56001(%rip), %rax ; (void *)0x000000010cdfd070: __stack_chk_guard
我不明白错在哪里!
如果我直接从主视图 Controller 在按钮上添加目标,则有效
A* a = [[A alloc] initWithImageView:self.imageView];
[A loadButtons];
for(B* b in a.b) {
[b.button addTarget:self action:@selector(bClicked:) forControlEvents:UIControlEventTouchUpInside];
}
最佳答案
单纯看你的A.h和A.m,有问题
- (id)initWithImageView:(UIImageView*)imageView {
self = [super init];
self.myArray = [[NSMutableArray alloc] init];
self.imageView = imageView;
return self;
}
- (void)loadButton {
B* b = [[B alloc] init];
[self.myArray addObject:b];
[self.imageView addSubview:b.button];
}
您的变量 b 将在 loadButton 方法退出后被释放!因此,即使您将 b.button 作为 subview 添加到 self.imageView,单击按钮也会使您的程序崩溃。
但在你的第二个例子中,
A* a = [[A alloc] initWithImageView:self.imageView];
[A loadButtons];
for(B* b in a.b) {
[b.button addTarget:self action:@selector(bClicked:) forControlEvents:UIControlEventTouchUpInside];
}
不知何故,b 是 A 的属性(为什么我在 A.h 中没有看到)?你修改了吗?如果您将 A.h 修改为包含指向 B 的强指针,则代码将起作用,因为您的 b 对象没有被释放。
关于objective-c - UIButton:单击时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29606173/