iOS開發UI篇—手勢辨識器(敲擊)

來源:互聯網
上載者:User

標籤:style   class   blog   code   tar   color   

iOS開發UI篇—手勢辨識器(敲擊)

 

一、監聽觸摸事件的做法

如果想監聽一個view上面的觸摸事件,之前的做法通常是:先自訂一個view,然後再實現view的touches方法,在方法內部實現具體處理代碼

通過touches方法監聽view觸摸事件,有很明顯的幾個缺點

(1)必須得自訂view

(2)由於是在view內部的touches方法中監聽觸摸事件,因此預設情況下,無法讓其他外界對象監聽view的觸摸事件(需要通過代理)

(3)不容易區分使用者的具體手勢行為

iOS 3.2之後,蘋果推出了手勢識別功能(Gesture Recognizer),在觸摸事件處理方面,大大簡化了開發人員的開發難度

 

二、手勢辨識器

為了完成手勢識別,必須藉助於手勢辨識器----UIGestureRecognizer

利用UIGestureRecognizer,能輕鬆識別使用者在某個view上面做的一些常見手勢

UIGestureRecognizer是一個抽象類別,定義了所有手勢的基本行為,使用它的子類才能處理具體的手勢

UITapGestureRecognizer(敲擊)

UIPinchGestureRecognizer(捏合,用於縮放)

UIPanGestureRecognizer(拖拽)

UISwipeGestureRecognizer(輕掃)

UIRotationGestureRecognizer(旋轉)

UILongPressGestureRecognizer(長按)

 

三、敲擊

每一個手勢辨識器的用法都差不多,比如UITapGestureRecognizer的使用步驟如下:

(1)建立手勢辨識器對象

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];

(2)設定手勢辨識器對象的具體屬性

// 連續敲擊2次

tap.numberOfTapsRequired = 2;

// 需要2根手指一起敲擊

tap.numberOfTouchesRequired = 2;

(3)添加手勢辨識器到對應的view上

[self.iconView addGestureRecognizer:tap];

(4)監聽手勢的觸發

[tap addTarget:self action:@selector(tapIconView:)];

屬性介紹:

numberOfTouchesRequired   //需要多少根手指一起敲擊(預設為1根)

numberOfTapsRequired    //需要敲擊多少下(預設為1)

 

四、實現代碼

 1 // 2 //  YYViewController.m 3 //  02-手勢辨識器(敲擊) 4 // 5 //  Created by apple on 14-6-18. 6 //  Copyright (c) 2014年 itcase. All rights reserved. 7 // 8  9 #import "YYViewController.h"10 11 @interface YYViewController ()12 @property (weak, nonatomic) IBOutlet UIImageView *iconView;13 14 @end15 16 @implementation YYViewController17 18 - (void)viewDidLoad19 {20     [super viewDidLoad];21     //0.設定imageview為可互動的22     self.iconView.userInteractionEnabled=YES;23 //    //1.建立手勢辨識器24 //    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] init];25 //    //2.設定手勢辨識器的具體屬性26 //    //設定敲擊的次數為雙擊(預設為單擊)27 //    tap.numberOfTapsRequired=2;28 //    //設定需要一根手指敲擊(預設)29 //    tap.numberOfTouchesRequired=1;30 //    //3.把手勢辨識器添加到對應的view上31 //    [self.iconView addGestureRecognizer:tap];32 //    //4.監聽手勢的觸發事件33 //    [tap addTarget:self action:@selector(tapView)];34     35     [self.iconView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapView)]];36 }37 -(void)tapView38 {39     NSLog(@"被點擊了");40 }41 42 43 @end

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.