您的位置:首页 > 其它

可以拖动的View

2016-02-23 10:27 246 查看
定义一个继承自UIview的类(即我们要移动的视图)

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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: