Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

objective c - Drag an UIImageView from UIscrollView to another view

I crawled all the web, but nothing.

I have a for loop to create uiimageview inside a uiscrollview controller. It's a collection of images that you can scroll horizontally only.

for (int i = 0; i < NIMAGES; i++) {
    NSString *filename = [NSString stringWithFormat:@"image%d.png", i+1];
    ScrollerImage *iv = [[ScrollerImage alloc] initWithNibName:@"ScrollerImage" bundle:nil];
    [iv initWithImage:[UIImage imageNamed:filename]];
    iv.frame = CGRectMake(i * 320.0f, 0.0f, 320.0f, 150.0f);
    iv.exclusiveTouch = YES;
    iv.userInteractionEnabled = YES;
    [sv addSubview:iv];
    [iv release];
}

The ScrollerImage class is an UIImageView controller

#import <UIKit/UIKit.h>
@interface ScrollerImage : UIImageView { 
}
@end

Now, how can I drag (not necessary a move, also a copy of view, or an id of view, anything that permit me to identify the image) an image from the scroller to another view? It's like a shopping cart, where you can drag items at the bottom view (cart).

Like this:
enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is an alternative, using UIGraphicsGetImageFromCurrentImageContext()

You can grab an image from currentScreen on click or after some events. Next renderize it to screen and apply a Pan gesture to move around the screen.

UIView *_DraggableView;
UIImageView *_imgvcChild1;

sample code:

- ( void ) onScrollviewClickOrOtherEvent
{
  UIGraphicsBeginImageContext ( _DraggableView.frame.size );
  [ _DraggableView.layer renderInContext:UIGraphicsGetCurrentContext() ];

  UIImage *grab = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  if ( _imgvcChild1 ) [ _imgvcChild1 removeFromSuperview ];
  _imgvcChild1 = [[ UIImageView alloc ] initWithImage:grab ];
  _imgvcChild1.frame = _DraggableView.frame;
  _imgvcChild1.userInteractionEnabled = YES;
  [ self.view addSubview:_imgvcChild1 ];

  UIPanGestureRecognizer *pan = [[ UIPanGestureRecognizer alloc ] initWithTarget:self action:@selector(moveObject:) ];
  [ pan setMinimumNumberOfTouches:1 ];
  [ _imgvcChild1 addGestureRecognizer:pan ];
}

- (void) moveObject:(UIPanGestureRecognizer *)pan
{
  _imgvcChild1.center = [ pan locationInView:_imgvcChild1.superview ];
}

--- EDIT ---

A sample project on github: https://github.com/elpsk/Shopping-Cart


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...