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

iOS 觸摸事件與搖一搖:UIView 跟手移動與隨機變色

編輯:iOS 開發綜合

這個範例示範兩件事:讓一個 view 跟著手指移動,以及用觸碰觸發隨機變色;同時順便走過 AppDelegate 的生命週期方法與搖一搖(motion)事件。

自訂 MyView:處理觸摸

關鍵在於記錄「手指按下的那一刻」的座標,再在移動時算出位移差,把差值套到自身的 center 上。

#import "MyView.h"

@interface MyView ()
// 記錄視圖開始(按下)時的座標
@property (nonatomic, assign) CGPoint startPoint;
@end

@implementation MyView

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // 一碰就隨機換色
    self.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0
                                           green:arc4random() % 256 / 255.0
                                            blue:arc4random() % 256 / 255.0
                                           alpha:1];

    NSLog(@"%ld", touches.count);          // 集合中有幾根手指

    UITouch *touch = [touches anyObject];  // 取出其中一個觸摸物件
    self.startPoint = [touch locationInView:self];  // 換算成自己座標系的位置
    NSLog(@"%g", self.startPoint.x);
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint movePoint = [touch locationInView:self];

    // 算出位移量
    CGFloat dx = movePoint.x - self.startPoint.x;
    CGFloat dy = movePoint.y - self.startPoint.y;

    // 把位移套到中心點上,view 就跟着手指跑了
    self.center = CGPointMake(self.center.x + dx, self.center.y + dy);
}

@end

MainViewController:生命週期與搖一搖

#import "MainViewController.h"

@interface MainViewController ()
@property (nonatomic, retain) UITextField *myTextField;
@end

@implementation MainViewController

- (void)dealloc {
    [_myTextField release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 注意:init / loadView / viewDidLoad 都只會跑一次,
    // 而 viewWillAppear 每次畫面出現都會跑
    self.myTextField = [[UITextField alloc] initWithFrame:CGRectMake(100, 500, 150, 40)];
    self.myTextField.layer.cornerRadius = 10;
    self.myTextField.layer.borderWidth = 2;
    [self.view addSubview:_myTextField];
    [_myTextField release];

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
    view.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:view];
    [view release];

    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
    button1.frame = CGRectMake(0, 0, 100, 100);
    button1.backgroundColor = [UIColor cyanColor];
    button1.layer.borderWidth = 1;
    button1.layer.cornerRadius = 10;
    [view addSubview:button1];
    [button1 addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];

    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];
    button2.frame = CGRectMake(150, 150, 100, 100);
    button2.backgroundColor = [UIColor blackColor];
    button2.layer.borderWidth = 1;
    button2.layer.cornerRadius = 10;
    [view addSubview:button2];
    [button2 addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 觸摸事件(此方法寫在 view controller 上)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"觸摸開始");
    [self.myTextField resignFirstResponder];   // 點空白處收起鍵盤
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event   { NSLog(@"觸摸結束"); }
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event   { NSLog(@"觸摸移動"); }
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { NSLog(@"觸摸被取消"); }

- (void)click:(UIButton *)button {
    NSLog(@"測試是否執行");
    [self.myTextField becomeFirstResponder];
}

#pragma mark - 搖一搖(Hardware > Simulate Motion 可測試)
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    NSLog(@"搖一搖開始");
    self.view.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0
                                               green:arc4random() % 256 / 255.0
                                                blue:arc4random() % 256 / 255.0
                                               alpha:1];
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event   { NSLog(@"搖一搖結束"); }
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event { NSLog(@"搖一搖被取消"); }

#pragma mark - 記憶體警告(Hardware > Simulate Memory Warning)
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    NSLog(@"記憶體警告");
}

@end

AppDelegate:手動建立視窗與根視圖

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    [_window release];

    MainViewController *mainVC = [[MainViewController alloc] init];
    self.window.rootViewController = mainVC;
    [mainVC release];

    return YES;
}

重點整理

  • 觸摸事件的傳遞順序:系統會先問 hit-test 出來的子視圖,子視圖不處理才往上冒泡到父視圖。所以 button 點擊不會觸發 view controller 的 touchesBegan:。
  • 四個觸摸階段:began → moved(可多次)→ ended/cancelled。來電或手勢插隊時會走 cancelled,記得處理,否則狀態可能卡在按下中。
  • 搖一搖屬於 motion 事件,與觸摸無關,要真正在裝置上實作搖動偵測通常會改用 Core Motion。
  • 視圖座標系:locationInView: 傳 self 得到的是相對自己的座標,傳 nil 則是相對視窗。跟手移動時兩次都必須用同一個座標系,位移才會正確。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved