可以拖动的View
2016-02-23 10:27
246 查看
定义一个继承自UIview的类(即我们要移动的视图)
BallView.h
BallView.m
接下来我们在根视图控制器中引入头文件,初始化加入视图即可
BallView.h
@interface BallView : UIView { CGPoint startPoint; } @end
BallView.m
@implementation BallView - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { // 获取触摸对象 UITouch *touch = [touches anyObject]; startPoint = [touch locationInView:self]; } - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { //获取触摸的对象 UITouch *touch = [touches anyObject]; CGPoint newPoint = [touch locationInView:self]; // 分别计算x y变动的距离 CGFloat dx = newPoint.x - startPoint.x; CGFloat dy = newPoint.y - startPoint.y; // 改变中心点坐标 self.center = CGPointMake(self.center.x + dx, self.center.y + dy); } @end
接下来我们在根视图控制器中引入头文件,初始化加入视图即可
- (void)viewDidLoad { [super viewDidLoad]; BallView *ball = [[BallView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; ball.backgroundColor = [UIColor redColor]; ball.layer.cornerRadius = ball.frame.size.width / 2; ball.layer.masksToBounds = YES; [self.view addSubview:ball]; }
相关文章推荐
- Android 开发之旅:view的几种布局方式及实践
- libnet_init()总是返回NULL的问题
- ubuntu创建虚拟硬盘
- EXCEL文档1.生成EXCEL文档,并生成压缩文件
- jQuery 操作导航栏
- Linux关闭sendmail服务
- fragment管理
- 第一个项目实践问题记录
- poj 1733 Parity game(带权并查集)
- 数据结构基础 之 图 的 邻接矩阵实现与邻接表实现
- 字符串比较
- 字符串链接strcat
- ZK 最少限度加载页面js文件
- dcpromo(server2012不支持)
- javaScript里的二维数组转换为json格式的字符串
- Android&java的成长之路之六(2048小游戏②)
- MapReduce工作原理图文详解
- SQLAlchemy 笔记 ORM方式访问数据库
- Redis学习到实战(一)基础与入门
- 修改oracle用户密码永不过期