您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 程式碼筆記:實作左右滑動手勢

編輯:iOS 開發綜合

本文為大家分享 iOS 中實作左右滑動操作的程式碼,供大家參考,具體內容如下。

一、效果圖

二、程式碼

RootViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"可以向左(右)滑動";

    //向右滑動
    UISwipeGestureRecognizer *recognizerLeft;
    recognizerLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFromLeft:)];
    [recognizerLeft setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [self.view addGestureRecognizer:recognizerLeft];

    //向左滑動
    UISwipeGestureRecognizer *recognizerRight;
    recognizerRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFromRight:)];
    [recognizerRight setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [self.view addGestureRecognizer:recognizerRight];
}

#pragma -mark -手勢滑動
//向左滑動
-(void)handleSwipeFromLeft:(UISwipeGestureRecognizer *)recognizer {
    NSLog(@"-------進入向左手勢滑動姿勢-------------");
    if (recognizer.direction==UISwipeGestureRecognizerDirectionLeft) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"進入向左手勢滑動姿勢" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil];
        [alert show];
    }
}

//向右滑動
-(void)handleSwipeFromRight:(UISwipeGestureRecognizer *)recognizer {
    NSLog(@"-------進入向右手勢滑動姿勢-------------");
    if (recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"進入向右手勢滑動姿勢" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil];
        [alert show];
    }
}

這個範例透過 UISwipeGestureRecognizer 來監聽使用者的滑動手勢。實作步驟很簡單:分別建立向左與向右的滑動辨識器,透過 setDirection: 指定要偵測的方向,再用 addGestureRecognizer: 把辨識器加到視圖上;最後在各自的回調方法中判斷 direction,並觸發對應的操作(此處以彈出提示框作示範)。這種手勢辨識機制常用於左右切換頁面、翻閱圖片或開啟側邊欄等互動場景。

以上就是本文的全部內容,希望對大家的學習有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved