iOS开发入门之——拖动视图
2012-03-23 19:01
417 查看
预备知识
iOS处理屏幕上的触摸动作,主要涉及到以下几个方法:touchesBegan:withEvent: //触摸屏幕的最开始被调用touchesMoved:withEvent: //移动过程中被调用touchesEnded:withEvent: //动作结束时被调用touchesCancelled:WithEvent:从方法的命名可以清晰的看出该方法何时被调用,最后一个比较特殊。touchesCancelled:WithEvent:在Cocoa Touch必须响应持续触摸事件的系统中断时调用。我们只要重写这些方法,来作我们想要作的事情就可以了。如何实现拖动视图?
1.设置userInteractionEnabled属性为YES,允许用户交互。2.在触摸动作开始时记录起始点。3.在移动过程中,计算当前位置坐标与起始点的差值,即偏移量,并且移动视图中心点至偏移量大小的地方。4.分别限制x坐标、与y坐标,保证用户不可将视图托出屏幕备注:分别限制x坐标与y坐标的原因是,即使向右拖动不了了,仍需保证可以向下拖动。
实现代码
以子类化UIImageView为例#import <UIKit/UIKit.h> @interface GragView : UIImageView { CGPoint startPoint; } @end
#import "GragView.h" @implementation GragView - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code //允许用户交互 self.userInteractionEnabled = YES; } return self; } - (id)initWithImage:(UIImage *)image { self = [super initWithImage:image]; if (self) { //允许用户交互 self.userInteractionEnabled = YES; } return self; } - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { //保存触摸起始点位置 CGPoint point = [[touches anyObject] locationInView:self]; startPoint = point; //该view置于最前 [[self superview] bringSubviewToFront:self]; } -(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { //计算位移=当前位置-起始位置 CGPoint point = [[touches anyObject] locationInView:self]; float dx = point.x - startPoint.x; float dy = point.y - startPoint.y; //计算移动后的view中心点 CGPoint newcenter = CGPointMake(self.center.x + dx, self.center.y + dy); /* 限制用户不可将视图托出屏幕 */ float halfx = CGRectGetMidX(self.bounds); //x坐标左边界 newcenter.x = MAX(halfx, newcenter.x); //x坐标右边界 newcenter.x = MIN(self.superview.bounds.size.width - halfx, newcenter.x); //y坐标同理 float halfy = CGRectGetMidY(self.bounds); newcenter.y = MAX(halfy, newcenter.y); newcenter.y = MIN(self.superview.bounds.size.height - halfy, newcenter.y); //移动view self.center = newcenter; } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code } */ @end
效果图
![](http://hi.csdn.net/attachment/201203/23/6157840_1332500606T122.gif)
相关文章推荐
- iOS开发入门之——拖动视图
- iOS开发入门之——拖动视图
- iOS开发入门之——可拖动视图
- iOS开发 控件不能绑定拖动到视图ViewController连接的解决方法
- 举例讲解iOS开发中拖动视图的实现
- IOS 初级开发入门教程(三)探究应用及视图的生命周期变化
- Cocoa Touch 入门记——《精通 iOS 开发》学习心得(3) [标签栏实现多视图的方法(运用 xib)]
- 【Facebook的UI开发框架React入门之五】视图View与文本Text简介(iOS平台)-goodmao
- 自学iOS开发系列----UI(视图编程入门:UIView)
- 自学iOS开发系列----UI(视图编程入门:UIButton)
- 自学iOS开发系列----UI(视图编程入门:UIGestureRecognizer)
- 自学iOS开发系列----UI(视图编程入门:ViewController、UIImageView、UILabel)
- 自学iOS开发系列----UI(视图编程入门:UITabBarController)
- iOS开发入门_视图控制器_UI_02
- IOS开发入门(12)-表视图I:基础知识
- iOS开发系列----UI(视图编程入门:Delegate、Block、单例、属性传值)
- 自学iOS开发系列----UI(视图编程入门:UINavigationController)
- ios开发入门- TabBarController使用和多视图切换
- 自学iOS开发系列----UI(视图编程入门:UIScrollView)
- IOS开发入门教程-总结篇-写给狂热的编程爱好者们