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];
}