UIView-4-EventForViews(在view上加入button时候的事件处理)

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //创建view对象
    UIView *myview = [[UIView alloc]init];
    myview.frame = CGRectMake(50, 100, 150, 100);
    [self.view addSubview:myview];
   
    //设置背景颜色
    myview.backgroundColor = [UIColor greenColor];
    
    //设置是否能接受事件,默认是YES
    myview.userInteractionEnabled = NO;
    
    //创建button
    UIButton * btn = [[UIButton alloc]init];
    btn.frame = CGRectMake(50, 100, 250, 40);
    [myview addSubview:btn];
    btn.backgroundColor = [UIColor redColor];
    
    //注册事件
    [btn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchDown];
    
    //1.如果父视图不能接受事件,则子视图也不能接受事件
    //2.子视图超出父视图的部分不能接受事件
    
    [btn removeFromSuperview];
    [self.view addSubview:btn];
    
    [self.view insertSubview:btn belowSubview:myview];
    //3.如果上面视图覆盖下面视图而且能接受事件,则下面视图不会收到事件了
    
    //4.UILabel和UIImageView 默认不能接受事件
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - button处理方法
- (void)onClick:(UIButton *)btn
{
    NSLog(@"button press!");
}

@end

posted @ 2015-09-17 06:50  阿凡提王  阅读(128)  评论(0编辑  收藏  举报