您的位置:首页 > 移动开发 > IOS开发

iOS开发中两层view上的button不响应点击事件

2016-01-26 11:13 459 查看


iOS button addTarget 无法响应事件

1.问题描述

封装了一个XYAlterview,继承于UIView,但button addTarget 无法响应事件.

2.问题重现

@interface XYAlertView : UIView
@end
XYAlterView的实现结构是:bgView ,alertBgView,button
` - (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];

if(self){
[self addSubview:bgView];

[bgview addSubview: alertBgView]

[button addTarget:self
action:@selector(buttonBeCick:)
forControlEvents:
UIControlEventTouchUpInside];

[alertBgView addSubview :button]

}

return self;

}
-(void)showAlertViewinSuperView:(UIView *)superView{
[superView addSubview:bgView];

}
然后就会导致button可以点击,即会表现出button可以点击,但是无法响应点击事件。

3.原因分析

分析原因是:
[superView addSubview:bgView];
此处只是将bgView添加到superView上面,但是没有将self添加到superView上面。self没有被引用,self没有被引用,所以不会响应
[button addTarget:self action:@selector(buttonBeCick:) forControlEvents:UIControlEventTouchUpInside];
注:button addTarget:self 就是指向XYAlertView

4.解决方案:

将self添加到superView上面,引用self,然后就可以响应button的点击事件

(void)showAlertViewinSuperView:(UIView *)superView{
[superView addSubview: self];


}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: