iOS-給UIView添加點擊事件


一.當遇到一些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

四.效果圖


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM