UIView拖动(图像和文字)

psi*_*kjr 27 iphone objective-c

是否有可能在iOS屏幕上拖动UIView同时具有图像和文本?例如小卡片.你能指点我类似的(已解决的)主题吗?我还没找到.

Ari*_*sky 36

基于pepouze的答案,这就是一个简洁的解决方案,看起来像(测试过,它有效!)

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *aTouch = [touches anyObject];
    CGPoint location = [aTouch locationInView:self];
    CGPoint previousLocation = [aTouch previousLocationInView:self];
    self.frame = CGRectOffset(self.frame, (location.x - previousLocation.x), (location.y - previousLocation.y));
}
Run Code Online (Sandbox Code Playgroud)


MHC*_*MHC 34

虽然UIView没有内置支持在用户拖动中移动自身,但实现它应该不是那么困难.当您只处理拖动视图时,它更容易,而不是其他操作,如点击,双击,多点触摸等.

首先要做的是DraggableView通过子类化UIView 来创建自定义视图.然后覆盖UIView的touchesMoved:withEvent:方法,您可以在那里获得当前拖动位置,并移动DraggableView.请看下面的例子.

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *aTouch = [touches anyObject];
    CGPoint location = [aTouch locationInView:self.superview];
    [UIView beginAnimations:@"Dragging A DraggableView" context:nil];
    self.frame = CGRectMake(location.x, location.y, 
                            self.frame.size.width, self.frame.size.height);
    [UIView commitAnimations];
}
Run Code Online (Sandbox Code Playgroud)

并且因为DraggableView对象的所有子视图也将被移动.因此,将所有图像和文本作为DraggableView对象的子视图.

我在这里实现的非常简单.但是,如果您希望拖动更复杂的行为(例如,用户必须点击视图几秒钟才能移动视图),那么您将不得不重写其他事件处理方法(touchesBegan:withEvent:和touchesEnd:withEvent).


Rok*_*arc 24

MHC答案的补充.

如果您不希望视图的左上角在您的手指下跳跃,您也可以touchesBegan 像这样覆盖:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *aTouch = [touches anyObject];

    offset = [aTouch locationInView: self];
}
Run Code Online (Sandbox Code Playgroud)

并改变MHC的触摸移动到:

 -(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
 {
      UITouch *aTouch = [touches anyObject];
      CGPoint location = [aTouch locationInView:self.superview];

      [UIView beginAnimations:@"Dragging A DraggableView" context:nil];
      self.frame = CGRectMake(location.x-offset.x, location.y-offset.y, 
                              self.frame.size.width, self.frame.size.height);
      [UIView commitAnimations];
  }
Run Code Online (Sandbox Code Playgroud)

你还应该CGPoint offset在界面中定义:

@interface DraggableView : UIView
{
    CGPoint offset;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

Arie Litovsky提供更优雅的解决方案,让您放弃伊娃:https://stackoverflow.com/a/10378382/653513


小智 5

即使rokjarc解决方案有效,使用

CGPoint previousLocation = [aTouch previousLocationInView:self.superview];
Run Code Online (Sandbox Code Playgroud)

避免CGPoint offset创建和调用touchesBegan:withEvent: