OObjective-c UIView 蒙層

ViewController.m文件ide


#import "ViewController.h"函數

@interface ViewController ()
佈局

{spa

    UIView1 *view1;.net

    UIButton *button;3d

}
orm

@end 對象

@implementation ViewController
事件

- (void)viewDidLoad {
get

    [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是指定響應對象的 弱 引用

相關文章
相關標籤/搜索