在做自定义弹出框的时候遇到一个问题,如下图:
原意是点击弹窗之外的蒙层整个view消失,点击弹窗内部则弹窗不消失。在做的过程中我为自定义的弹窗view设置了点击事件:
<span style="font-size:18px;">UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedBackGroundView)];
[view addGestureRecognizer:tapGesture];</span>
能够实现点击弹窗外的地方整个弹出层消失。但是在点击弹窗内部时整个弹出层也消失了。后来想了想原因,因为弹窗是加在弹出层上的,根据IOS事件传递,当点击弹框弹出层也会接收到点击事件,所以就导致整个弹出层消失。想想解决办法,估计可以在弹窗消失的事件中判断,如果点击区域为弹窗则不消失,这种方法理论上应该是可行的,没有亲自试过。我用的是UIControl帮助解决的。
打开UIControl源码可以看到其本质是一个UIView,里面有个addTarget方法;我们通常用的UIButton、UISegmentedControl等都是继承自UIControl实现的。可以参考http://m.blog.youkuaiyun.com/blog/catandrat111/8539101
我的做法是在弹出层添加UIControl,然后再在弹出层添加弹出框(UIControl必须在弹出框之前添加):
UIControl *control=[[UIControl alloc] initWithFrame:[UIScreen mainScreen].bounds];
[control addTarget:self action:@selector(tappedCancel) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:control];//先添加UIControl <span style="font-family: Arial, Helvetica, sans-serif;">[self addSubview:tckView]//后添加弹出框</span>
这样就可以实现需要的效果了。