iPhone开发进阶(8)--- 检测屏幕触摸事件

From:http://www.2cto.com/kf/201110/108295.html

 

这一回来定制UIView 上的触摸事件,作为例子,只是简单地检测出触摸事件并显示当前坐标在控制台上。

 

首先添加新文件,如下图:


      

 

在显示的对话框中选中Cocoa Touch Class 的Objective C class ⇒UIView

 

      在项目的添加菜单中选择Touch 。检测触摸时间需要实现下面的函数。

 

 

 - (void)touchesBegan:(NSSet *)touches

withEvent:(UIEvent *)event;

这个函数由用户触摸屏幕以后立刻被调到。为了自定义他的行为,我们像下面来实现:

 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch* touch = [touches anyObject];

    CGPoint pt = [touch locationInView:self];

    printf("point = %lf,%lf\n", pt.x, pt.y);

}

上面的代码将触摸点的坐标取出,并打印到控制台上。

 

如果需要得到多点触摸(不只是一根手指)的信息,需要使用anyObject 实例指定UIView。

 

另外,TouchAppDelegate 的applicationDidFinishLaunching 函数像下面一样实现:

 

 - (void)applicationDidFinishLaunching:(UIApplication *)application {

    TouchView* view = [[TouchView alloc]

        initWithFrame:CGRectMake(100, 100, 200, 200)];

    view.backgroundColor = [UIColor greenColor];

    [window addSubview:view];

    [window makeKeyAndVisible];

    [view release];

}

这里用intiWithFrame 指定的矩形区域可以任意。另外为了明确触摸的区域大小,设定其view.backgroundColor。

 

虽然通过initWithFrame 在TouchAppDelegate 内创建了TouchView 的实例、但是通过addSubview:view 将管理责任交给了window 。就是说,TouchAppDelegate 与window 两个实例都对TouchView 实例实施管理。所以这里用[view release] 释放TouchAppDelegate 的管理责任

摘自:易飞扬

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值