1.UIGestureRecognizer 的子類玷坠,開發(fā)時(shí)可以直接調(diào)用
UIPanGestureRecognizer(拖動)
UIPinchGestureRecognizer(捏合)
UIRotationGestureRecognizer(旋轉(zhuǎn))
UITapGestureRecognizer(點(diǎn)按)
UILongPressGestureRecognizer(長按)
?UISwipeGestureRecognizer(輕掃)
當(dāng)然,如果繼承UIGestureRecognizer也可以自定義手勢劲藐。
自定義手勢時(shí)八堡,需要 #import<UIKit/UIGestureRecognizerSubclass.h>一般需實(shí)現(xiàn)如下方法:
- (void)reset;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
//以上方法在分類 UIGestureRecognizer (UIGestureRecognizerProtected) 中聲明,更多方法聲明請自行查看
2.UIGestureRecognizer 的繼承關(guān)系
3.手勢狀態(tài)
手勢分為離散型和連續(xù)型手勢聘芜,在以上6種的手勢中兄渺,只有UITapGestureRecognizer(點(diǎn)按)是離散型手勢,即一旦識別就無法取消汰现,而且只會調(diào)用一次操作事件挂谍。
而離散型手勢會多次調(diào)用操作事件,并且可以被取消瞎饲。
手勢被識別的過程狀態(tài)如下:
typedef NS_ENUM(NSInteger, UIGestureRecognizerState) {
UIGestureRecognizerStatePossible,? // 尚未識別是何種手勢操作(但可能已經(jīng)觸發(fā)了觸摸事件)口叙,默認(rèn)狀態(tài)
UIGestureRecognizerStateBegan,? ? ? // 手勢已經(jīng)開始,此時(shí)已經(jīng)被識別嗅战,但是這個(gè)過程中可能發(fā)生變化妄田,手勢操作尚未完成
UIGestureRecognizerStateChanged,? ? // 手勢狀態(tài)發(fā)生轉(zhuǎn)變
UIGestureRecognizerStateEnded,? ? ? // 手勢識別操作完成(此時(shí)已經(jīng)松開手指)
UIGestureRecognizerStateCancelled,? // 手勢被取消,恢復(fù)到默認(rèn)狀態(tài)
UIGestureRecognizerStateFailed,? ? // 手勢識別失敗驮捍,恢復(fù)到默認(rèn)狀態(tài)
UIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded // 手勢識別完成疟呐,同UIGestureRecognizerStateEnded
};
4.使用手勢的步驟
使用手勢很簡單,分為三步:
1.創(chuàng)建手勢識別器對象實(shí)例东且。創(chuàng)建時(shí)启具,指定一個(gè)回調(diào)方法,當(dāng)手勢開始珊泳,改變富纸、或結(jié)束時(shí)囤踩,執(zhí)行回調(diào)方法旨椒。
2.設(shè)置手勢識別器對象實(shí)例的相關(guān)屬性(可選部分)
3.添加到需要識別的 View 中晓褪。每個(gè)手勢只對應(yīng)一個(gè) View,當(dāng)屏幕觸摸在 View 的邊界內(nèi)時(shí)综慎,如果手勢和預(yù)定的一樣涣仿,那就會執(zhí)行回調(diào)方法。
PS:一個(gè)手勢只能對應(yīng)一個(gè) View示惊,但是一個(gè) View 可以有多個(gè)手勢好港。建議在真機(jī)上測試這些手勢,模擬器操作不太方便米罚,可能導(dǎo)致認(rèn)為手勢失效的情況。(模擬器測試捏合和旋轉(zhuǎn)手勢時(shí),按住 option 鍵橡娄,再用觸摸板或鼠標(biāo)操作)
@property (nonatomic, strong) UISwipeGestureRecognizer *leftSwipeGestureRecognizer;
- (void)addGestureRecognizer {
//第一步立美,創(chuàng)建滑動手勢并且初始化
self.leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightItemTapped)];
//設(shè)置滑動手勢是向左滑動時(shí)觸發(fā)
self.leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
//給視圖添加上手勢
[self.view addGestureRecognizer:self.leftSwipeGestureRecognizer];
}