MST

星途 面试题库

面试题:Objective-C中如何实现简单的点击手势识别

请简述在Objective-C中,为一个视图添加点击手势识别的基本步骤,并给出关键代码示例。
13.7万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试
  1. 基本步骤
    • 创建手势识别器对象,例如UITapGestureRecognizer
    • 设置手势识别器的目标和动作,即指定当手势发生时调用哪个对象的哪个方法。
    • 将手势识别器添加到需要识别手势的视图上。
  2. 关键代码示例
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建UITapGestureRecognizer对象,设置点击次数为1
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    // 将手势识别器添加到视图上
    [self.view addGestureRecognizer:tapGesture];
}

// 处理点击手势的方法
- (void)handleTap:(UITapGestureRecognizer *)sender {
    NSLog(@"View was tapped!");
}

@end