ios 怎么拖拽自定义view

 我来答
潇洒出风尘尘
2017-02-13 · 超过176用户采纳过TA的回答
知道答主
回答量:233
采纳率:0%
帮助的人:204万
展开全部
这个版本是基于viewcontroller的实现,并未子类化view;self.localview是你持有的小窗口,beginpoint需要你在viewcontroller中自己定义

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if (!self.isInView) // 仅当取到touch的view是小窗口时,我们才响应触控,否则直接return
{
return;
}

UITouch *touch = [touches anyObject];
CGPoint currentPosition = [touch locationInView:self.localView];
//偏移量
float offsetX = currentPosition.x - beginpoint.x;
float offsetY = currentPosition.y - beginpoint.y;
//移动后的中心坐标
self.localView.center = CGPointMake(self.localView.center.x + offsetX, self.localView.center.y + offsetY);

//x轴左右极限坐标
if (self.localView.center.x > (self.localView.superview.frame.size.width-self.localView.frame.size.width/2))
{
CGFloat x = self.localView.superview.frame.size.width-self.localView.frame.size.width/2;
self.localView.center = CGPointMake(x, self.localView.center.y + offsetY);
}
else if (self.localView.center.x < self.localView.frame.size.width/2)
{
CGFloat x = self.localView.frame.size.width/2;
self.localView.center = CGPointMake(x, self.localView.center.y + offsetY);
}

//y轴上下极限坐标
if (self.localView.center.y > (self.localView.superview.frame.size.height-self.localView.frame.size.height/2))
{
CGFloat x = self.localView.center.x;
CGFloat y = self.localView.superview.frame.size.height-self.localView.frame.size.height/2;
self.localView.center = CGPointMake(x, y);
}
else if (self.localView.center.y <= self.localView.frame.size.height/2)
{
CGFloat x = self.localView.center.x;
CGFloat y = self.localView.frame.size.height/2;
self.localView.center = CGPointMake(x, y);
}
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if (touch.view.frame.size.width == 120) // 120为小窗口的宽度(简单起见这里使用硬编码示例),用来判断触控范围;仅当取到touch的view是小窗口时,我们才响应触控
{
self.isInView = YES;
}
else
{
self.isInView = NO;
}
beginpoint = [touch locationInView:self.localView];

[super touchesBegan:touches withEvent:event];
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式