【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
ViewController.m文件
#import "ViewController.h"
@interface ViewController ()
{
UIView1 *view1;
UIButton *button;
}
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
button=[[UIButton alloc]initWithFrame:CGRectMake(100, 300, 60, 20)];
[button setTitle:@"点击" forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[self.view addSubview:button];
[button addTarget:self action:@selector(dianji1) forControlEvents:UIControlEventTouchUpInside];
[self layout];
}
-(void)dianji1{
NSLog(@"蒙层下的button被点击拉");
}
-(void)layout{
view1=[[UIView1 alloc]initWithFrame:[UIScreen mainScreen].bounds];
view1.backgroundColor=[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.5];
[self.view addSubview:view1];
//开启交互
view1.userInteractionEnabled=YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
___________________________________________________________________________________
UIView1.m文件
#import "UIView1.h"
@implementation UIView1
-(void)drawRect:(CGRect)rect{
button1=[[UIButton alloc]initWithFrame:CGRectMake(100, 100, 60, 20)];
[button1 setTitle:@"点击" forState:UIControlStateNormal];
[button1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[self addSubview:button1];
[button1 addTarget:self action:@selector(dianji1) forControlEvents:UIControlEventTouchUpInside];
}
-(void)dianji1{
NSLog(@"蒙层上的button被点击拉");
}
-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
UIView *hitView = [super hitTest:point withEvent:event];
if (hitView == self)
{
return nil;
}
else
{
return hitView;
}
}
@end
hitTest的用法:
(1)当在一个view上添加一个屏蔽罩,但又不影响对下面view的操作,也就是可以透过屏蔽罩对下面的view进行操作,这个函数就很好用了。
将下面的函数添加到UIView的子类中,也就是屏蔽罩类中即可。
-(id)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
UIView *hitView = [super hitTest:point withEvent:event];
if (hitView == self)
{
return nil;
}
else
{
return hitView;
}
}
(2)父视图中有布局重叠的且都可响应用户操作的对象,如:ScrollView and Button,如果Button在ScrollView下面,正常情况下Button是不会成为第一响应者的,如果想让Button可以响应在其布局内的触摸事件,可以在Button和ScrollView的父View中重写hitTest:withEvent方法
(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
CGPoint hitPoint = [_testButton convertPoint:point fromView:self];
if ([_testButton pointInside:hitPoint withEvent:event])
return _testButton;
return [super hitTest:point withEvent:event];
}//_testButton是指定响应对象的 弱 引用
来源:oschina
链接:https://my.oschina.net/u/2483781/blog/547852