iOS_满聪

想要源码的朋友,可以留下QQ邮箱.
  博客园  :: 新随笔  :: 管理

iOS-给UIView添加点击事件

Posted on 2016-01-15 10:00  iOS_满聪  阅读(14699)  评论(0编辑  收藏  举报

一.当遇到一些UIView 或者 UIView的子类时,比如点击UIImageView要放大图片等。

二.步骤:

   1.首先要确保打开控件的用户交互,userInteractionEnabled设置成YES;

   2.创建手势,也就是用UITapGestureRecognizer类创建一个对象。

   3.将手势添加到需要的控件上。

  4.点击事件之后的处理,放在了手势的点击事件里。

三.代码区域

#import "ViewController.h"

@interface ViewController ()

{

    UIView     *_view;

    BOOL        _isSmall;        //标志view是大试图还是小试图

}

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    

    // 初始是小试图

    _isSmall = YES;

 

    _view = [[UIView alloc] init];

    

    //打开用户交互(不可少)

    _view.userInteractionEnabled = YES;

    

    _view.frame = CGRectMake(0, 20, 60, 60);

    _view.backgroundColor = [UIColor orangeColor];

    [self.view addSubview:_view];

    

    //添加手势

    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(event:)];

    

    //将手势添加到需要相应的view中去

    [_view addGestureRecognizer:tapGesture];

    

    //选择触发事件的方式(默认单机触发)

    [tapGesture setNumberOfTapsRequired:1];

}

 

#pragma mark 执行触发的方法

- (void)event:(UITapGestureRecognizer *)gesture

{

    CGRect rect1 = CGRectMake(0, 20, 120, 120);

    CGRect rect2 = CGRectMake(0, 20, 60, 60);

    

    

    if (_isSmall) {

        _view.frame = rect1;

        _isSmall = NO;

    }

    else

    {

        _view.frame = rect2;

        _isSmall = YES;

    }

   

}

@end

四.效果图