how to drag dynamically created UIImageview in obj c (xcode) - ios

i have gone through the many tutorials to drag an image on screen using touchesmoved method
but most of them are not for dynamically created imageviews
in my project i created 5 UIImageview programatically,
now i want that user can drag them on screen>> i also follow this answer
Question but all in vain , no success so far>
the code for creating the dynamically imageview is
for (int i = 0; i < index ; i++)
{
UIImageView *imageView1 = [[UIImageView alloc] initWithImage:
[UIImageimageNamed:image_name]];
self.imageView1.userInteractionEnabled = YES;
imageView1.frame = CGRectMake(xvalue, yvalue, 80.0f, 80.0f);
self.view.userInteractionEnabled = YES;
[self.view addSubview:imageView1];
}
Thanks in advance for good replies

I'm a little confused with how you are creating UIImageViews because you are using a for-loop but a static name. So you might have 15 UIImageViews with the name "imageView1".
But anyways, this shouldn't matter at all if you are using the code in the question you linked to. Perhaps you put the lines in out of order... this is the proper order. (If it doesn't work let me know, along with the errors you get)
//-(void)ViewDidLoad? {???? is this your function??
int xvalue = 0;//?? not sure where you declared these
int yvalue = 0;//?? not sure where you declared these
for (int i = 0; i < index ; i++) {
UIImageView *imageView1 = [[UIImageView alloc] initWithImage:
[UIImageimageNamed:image_name]];
self.imageView1.userInteractionEnabled = YES;
imageView1.frame = CGRectMake(xvalue, yvalue, 80.0f, 80.0f);
self.view.userInteractionEnabled = YES;
[self.view addSubview:imageView1];
}
self.elements=[myElements getElements];
imagesElements = [[NSMutableArray alloc]init];
for(ElemetsList *item in self.elements) {
UIImageView *oneelement = [[UIImageView alloc] initWithImage:[UIImage imageNamed:item.imgElement]];
oneelement.frame = CGRectMake(item.positionX, item.positionY, item.width, item.height);
oneelement.userInteractionEnabled=YES;
[imagesElements addObject:oneelement];
}
for(UIImageView *img in imagesElements) {
[self.view addSubview:img];
}
//}? End Function, whatever it may be...?
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
for(UIImageView *img in imagesElements)
{
if([self view] == img)
{
CGPoint location = [touch locationInView:self.view];
img.center=location;
}
}
}
If you just want to hard-code in the moving for one image try this:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
imageView1.center=[touch locationInView:self.view];
}

There are plenty of ways to address this issue. You can add UIPanGestureRecognizer to each UIImageView at the time its creation, or you can use touchesBegan:, touchesMoved: on self (assuming it's a UIViewController) and traverse each UIImageView to see if its frame contains the point of the touch.

Related

How to move array of UIImageViews smoothly?

Am working on kind of seating arrangement application. Where the app allows the admin to arrange the seatings by click and move the each seat and then save the seating arrangement with frame sizes of each seat. I tried by loading 5 UIImageView on custom view and move the imageview but, only one imageview is getting moved. Rest of the imageviews not getting moved. Can you please help me on this?
- (void) addSeatsToTheView {
for (int i=0; i<5; i++) {
self.hotelImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 50, 50)];
self.hotelImage.image = [UIImage imageNamed:#"DiningIcon"];
self.hotelImage.userInteractionEnabled = YES;
[self.hotelImage setUserInteractionEnabled:YES];
self.hotelImage.tag = i;
[self.hotelView addSubview:self.hotelImage];
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if (touch.view == self.hotelImage) {
CGPoint location = [touch locationInView:self.hotelView];
NSLog(#"Begen Touch Location: %#", NSStringFromCGPoint(location));
self.hotelImage.frame=CGRectMake(location.x, location.y, 50, 50);
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if (touch.view == self.hotelImage) {
CGPoint location = [touch locationInView:self.hotelView];
NSLog(#"Begen Touch Location: %#", NSStringFromCGPoint(location));
self.hotelImage.frame=CGRectMake(location.x, location.y, 50, 50);
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if (touch.view == self.hotelImage) {
CGPoint location = [touch locationInView:self.hotelView];
NSLog(#"Begen Touch Location: %#", NSStringFromCGPoint(location));
self.hotelImage.frame=CGRectMake(location.x, location.y, 50, 50);
}
}
Once the admin arranged the seatings we have to save all the visible uiimageview framesizes. Thanks.
Edited:
I tried the using UIPanGestureRecognizer but, only one imageview getting moved. Don't know where am doing wrong? Can you please help me? Thanks.
- (void) addSeatsToTheView {
for (int i=0; i<5; i++) {
self.hotelImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 50, 50)];
self.hotelImage.image = [UIImage imageNamed:#"DiningIcon"];
self.hotelImage.userInteractionEnabled = YES;
[self.hotelImage setUserInteractionEnabled:YES];
self.hotelImage.tag = i;
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(gestureRecognizerMethod:)];
[self.hotelImage addGestureRecognizer:panGestureRecognizer];
[self.hotelView addSubview:self.hotelImage];
}
}
- (void)gestureRecognizerMethod:(UIPanGestureRecognizer *)recogniser
{
if (recogniser.state == UIGestureRecognizerStateBegan || recogniser.state == UIGestureRecognizerStateChanged)
{
CGPoint touchLocation = [recogniser locationInView:self.hotelView];
self.hotelImage.frame = CGRectMake(touchLocation.x, touchLocation.y, 50, 50);
}
}
Don't use touches methods for this; you'll go insane. Make each image view user-interactive and give it a UIPanGestureRecognizer. There is standard code for the pan gesture recognizer's action handler for following a finger, i.e. making the view draggable.
Once you've done that, everything stems from your misuse of self.hotelImage. Get rid of it entirely. In your for loop, just use a local variable, UIImageView* hotelImage = .... In the gesture recognizer method, use [recogniser view] to refer to the image view to which this gesture recognizer is attached. Everything will sort itself out after that!

Add a uiimageview inside a uiview when touching the uivew

What I want to do is when I touch the UIView, I want to add an image at the touched location.
This is my code I have for the moment.
(I have tried to replace x and y with touchLocation in the CGRectMake, but that doesn't work).
Edited
After clean and restart xcode it work.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInView:touch.view];
if ([touch view] == GrassView) {
NSLog(#"Hit grass");
UIImageView *imageViewFlower =[[UIImageView alloc] initWithFrame:CGRectMake(0,0,50,50)];
imageViewFlower.center = touchLocation;
imageViewFlower.image= [UIImage imageNamed:#"whiteflower.png"];
[GrassView addSubview:imageViewFlower];
}
}
Thanks for any help!
try to change the imageViewFlower insertion code in the if branch with the following code:
UIImageView *imageViewFlower =[[UIImageView alloc] initWithFrame:CGRectMake(touchLocation.x-25,touchLocation.y-25,50,50)];
imageViewFlower.image = [UIImage imageNamed:#"whiteflower.png"];
[GrassView addSubview:imageViewFlower];
After clean and restart xcode the code works fine.

iOS - How To Draw Point On A Line In Which The User Touches When Dragging

I have a rectangular view which contains vertical thin lines in which I drew programatically.
This is the code I used to draw the lines:
- (void)drawLines
{
CGFloat spacing = _bgView.frame.size.width / 11.0f;
for(int i = 1; i < 11; i++)
{
UIView *line = [[UIView alloc] initWithFrame:CGRectMake((CGFloat)(i * spacing), 0, 1, _bgView.frame.size.height)];
line.backgroundColor = [UIColor whiteColor];
line.tag = i;
[_bgView addSubview:line];
}
}
The lines are separated by equally distributed spaces calculated from the width of the rectangular view(_bgView).
Here's an overview of what it looks like:
When the user performs a drag in the rectangular view, and when his/her finger passes through or touches a line, a dot will be drawn on that specific point.
Here's the code that detects the point of touch of the user on the line, and draws a dot on that point.
- (IBAction)drawDots:(id)sender
{
UIPanGestureRecognizer *pan = (UIPanGestureRecognizer *)sender;
CGPoint pannedPoint = [pan locationInView:_bgView];
for (UIView *subview in _bgView.subviews)
{
if (CGRectContainsPoint(subview.frame, pannedPoint) && subview.tag > 0)
{
NSLog(#"Point x:%.2f y:%.2f TAG:%i", pannedPoint.x, pannedPoint.y, subview.tag);
UIView *point = [[UIView alloc] initWithFrame:CGRectMake(pannedPoint.x - 2.5, pannedPoint.y - 2.5, 5, 5)];
point.backgroundColor = [UIColor redColor];
[_bgView addSubview:point];
}
}
}
Now, if the user pans really fast, this will be the result:
As can be seen, only some points are drawn, that's why there are a lot of missing dots on the other lines.
This should be expected result:
But, this happens only when the user pans super slow.
How can I draw the points in the lines intercepted by the touch of the user even if his finger moved really fast?
Thanks!
Instead of pan gestures you should use UIResponder methods to detect user touches:
- touchesBegan:withEvent:
- touchesMoved:withEvent:
- touchesEnded:withEvent:
- touchesCancelled:withEvent:
The second method - touchesMoved:withEvent: calls when user keeps moving its finger through the screen, so you can get its finger location:
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:touch.view];
Then just add your detection logic.
Check the docs for more details:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/
please refer this code
for your requirement
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
// NSLog(#"DEBUG: Touches moved" );
[super touchesMoved:touches withEvent:event];
if ([[event allTouches] count] > 1) {
} else {
UITouch *touch = [[event allTouches] anyObject];
UIView *view = touch.view;
NSLog(#"DEBUG: Touches Moved");
CGPoint location = [touch locationInView:self.bgView];
for (UIView *subview in _bgView.subviews)
{
if (CGRectContainsPoint(subview.frame, location) && subview.tag > 0) {
NSLog(#"Point x:%.2f y:%.2f TAG:%i", location.x, location.y, subview.tag);
UIView *point = [[UIView alloc] initWithFrame:CGRectMake(location.x - 2.5, location.y - 2.5, 5, 5)];
point.backgroundColor = [UIColor redColor];
[_bgView addSubview:point];
}
}
}
}
Will help you

Drag UIImageView images using UITouch Methods

I have a UITableViewCell with UIImageViews embedded. I understand it's not common practice but I'm using the UITouch methods to accomplish horizontal swipes. I retrieve images from a url/api . The issue is I wish to drag one image at a time from either left to right. The problem is, when i drag my finger on across the imageView, all loaded images slide through quickly. I want to focus on one image at a time during the drag. Hope I was clear.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
startLocation = [[touches anyObject] locationInView:self];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint point = [[touches anyObject] locationInView:self];
UITouch * touch = [touches anyObject];
self.viewOne.center = CGPointMake(self.viewOne.center.x+point.x - startLocation.x, self.viewOne.center.y);
if (startLocation.x < point.x) {
//Swipe Right
if ([self.photo.photoURLS isKindOfClass:[NSArray class]]) {
if (self.isSwiping == NO) {
self.isSwiping = YES;
self.currentImage--;
if (self.currentImage == -1) {
self.currentImage = 12;
}
self.viewBack.frame = CGRectMake(-self.frame.size.width,0.0f, self.frame.size.width, self.frame.size.height);
self.viewBack.hidden = NO;
self.loadingImage.hidden = NO;
NSURL *imageURL = [[NSURL alloc] initWithString:self.photo.photoURLS[self.currentImage]];
[self asyncLoadImageFromURL:imageURL andPhotoID:self.photo.id withCallback:^(UIImage *image, NSString *photoID) {
self.loadingImage.hidden = YES;
[imageCache setImage:image forKey:self.photo.photoURLS[self.currentImage]];
self.viewBack.image = image;
//new
self.viewOne.frame = CGRectMake(0.0f, 0.0f, self.frame.size.width, self.frame.size.height);
self.viewOne.image = self.viewBack.image;
self.isSwiping = NO;
self.pageControl.currentPage = self.currentImage;
self.viewBack.hidden = YES;
}];
}
}
}
} else {
//Swipe Left
}
}
It's not entirely clear what you're asking or what the issue is, but the following lines are suspect:
CGPoint point = [[touches anyObject] locationInView:self.vehicleImage];
self.viewOne.center = CGPointMake(self.viewOne.center.x+point.x -startLocation.x, self.viewOne.center.y);
if (startLocation.x < endLocation.x)
You are not setting endLocation until after you've finished touching the screen. During your touchesMoved responder, you'll be using bad endLocation data. You should be using the value of point in this function to determine motion.
It's also not really clear what is the relationship between self.vehicleImage and self.viewOne. If self.vehicleImage is a subview of self.viewOne (or otherwise moves during your frame changes), your locationInView will return seemingly inconsistent values, exaggerating the motion of your finger. Instead, you should be picking a view that will stay static during this process (perhaps your ViewController's self.view).

Adding drag and drop component to iOS app

I apologise if this seems very vague but I'm not sure how else to word it.
I am trying to build an ipad app that will let users populate a workspace with tools they need. I need an example of letting a user drag and drop components into the app interface. So for example if i had an app that the user can make a form and I want the user to be able to drag text boxes, lists, radio buttons etc to make the form, how would i go about doing that? The items that i am using will be in a popup menu so that the user drags up and then will see all the items that i need inside that popup. Im just not sure how to let them drag from the popup to the canvas and also be able to reuse the same item (so have 3 or 4 text boxes in the example). Is this possible? Can anyone direct me to a tutorial on this? I have searched but cant find anything.
If this is laid out wrong or is a stupid quest please let me know how to do it, this is my first time posting on here.
Thank you
There are already many answers explaining this question.
Basically you can make custom UIView, which after touching will be following the touch movement.
Something like this:
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
_originalPosition = self.view.center;
_touchOffset = CGPointMake(self.view.center.x-position.x,self.view.center.y-position.y);
}
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint position = [touch locationInView: self.view.superview];
[UIView animateWithDuration:.001
delay:0.0
options:UIViewAnimationOptionCurveEaseInOut
animations:^ {
self.view.center = CGPointMake(position.x+_touchOffset.x, position.y+_touchOffset.y);
}
completion:^(BOOL finished) {}];
}
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint positionInView = [touch locationInView:self.view];
CGPoint newPosition;
if (CGRectContainsPoint(_desiredView.frame, positionInView)) {
newPosition = positionInView;
// _desiredView is view where the user can drag the view
} else {
newPosition = _originalPosition;
// its outside the desired view so lets move the view back to start position
}
[UIView animateWithDuration:0.4
delay:0.0
options:UIViewAnimationOptionCurveEaseInOut
animations:^ {
self.view.center = newPosition
// to
}
completion:^(BOOL finished) {}];
}
Similar questions
iPhone App: implementation of Drag and drop images in UIView
Basic Drag and Drop in iOS
iPhone drag/drop
From the Question i thing you are going to Build a feature like Add to cart in Most of the Shopping Apps like Amazon, Flip kart and etc..
- (void)viewDidLoad {
[super viewDidLoad];
shoeImageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(46,222, 51 , 51)];
shoeImageView1.image = [UIImage imageNamed:#"shoe.png"];
shoeImageView2 = [[UIImageView alloc]initWithFrame:CGRectMake(150,222, 51 , 51)];
shoeImageView2.image = [UIImage imageNamed:#"shoe1.png"];
shoeImageView3 = [[UIImageView alloc]initWithFrame:CGRectMake(225,222, 51 , 51)];
shoeImageView3.image = [UIImage imageNamed:#"shoe2.png"];
addTOCart = [[UIImageView alloc]initWithFrame:CGRectMake(132,400, 80, 80)];
addTOCart.image = [UIImage imageNamed:#"basket.png"];
[self.view addSubview:addTOCart];
imageViewArray = [[NSMutableArray alloc]initWithObjects: shoeImageView1,shoeImageView2 ,shoeImageView3,nil];
for (int i=0; i<imageViewArray.count; i++) {
[self.view addSubview:[imageViewArray objectAtIndex:i]];
[[imageViewArray objectAtIndex:i]setUserInteractionEnabled:YES];
//[self touchesBegan:imageViewArray[i] withEvent:nil];
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
for(int i=0 ; i< imageViewArray.count; i++)
{
CGPoint pt = [[touches anyObject]locationInView:self.view];
startLocation = pt;
newtemp = [imageViewArray objectAtIndex:i];
UITouch* bTouch = [touches anyObject];
if ([bTouch.view isEqual:newtemp])
{
firstTouchPoint = [bTouch locationInView:[self view]];
oldX = firstTouchPoint.x - [[bTouch view]center].x;
oldY = firstTouchPoint.y - [[bTouch view]center].y;
}
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
for(int i=0 ; i< imageViewArray.count; i++)
{
newtemp = [imageViewArray objectAtIndex:i];
//oldLoc = newtemp.frame;
if (CGRectContainsPoint(addTOCart.frame , newtemp.frame.origin))
{
NSLog(#"touched");
dragging = NO;
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Cart" message:#"Added to Cart" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[[imageViewArray objectAtIndex:i] setImage:[UIImage imageNamed:#""]];
[imageViewArray removeObjectAtIndex:i];
[alert show];
break;
}
else
{
//[newtemp setCenter:CGPointMake(startLocation.x-oldX, startLocation.y-oldY)];
}
// self.view.userInteractionEnabled= NO;
}
dragging = NO;
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* mTouch = [touches anyObject];
// if ([mTouch.view isEqual: newtemp]) {
CGPoint cp = [mTouch locationInView:[self view]];
[[mTouch view]setCenter:CGPointMake(cp.x-oldX, cp.y-oldY)];
// }
}
you can use these codes to implement these feauture. Using these code u can drag the object any where in the screen.
for sample project you can use this Link.

Resources