Question

I am just trying to plan a new app... I want to have a series of images which a user can drag around the screen and drop where they want.

I'm thinking that I will have an array (NSMutableArray) of all the images. when the app loads, it will draw these out to a scrollable UIView... then the app will know which a user has pressed and dragged in to the main view.

I can code it so one image can be dragged, but I'm not sure how to apply the same code to n number of images. For example, in my view controller, I set IBOutlet UIImage *image which in IB I can link and control.... but how do you change this to apply to any number of images?

I've tried searching for this all morning but haven't had much luck.

I am thinking I'd need to apply a class to each image as I draw it out of the array. I'm just after a little advice here really - maybe pointing me in the right direction?

Thanks for any info!!

Was it helpful?

Solution

First, you need to logically separate your data, in this case images, from the views that display them. To display and position images you put them UIImageViews. The images should be stored in a some kind of data structure e.g. array, dictionary, database etc. Then you should load them into one or more UIImageViews as needed.

If you have a highly variable number of interface elements it is best to create the variable elements programatically. In your case, you would wire up in Interface Builder the fixed elements like the scrollview. Then when you needed to add an image you initialize a UIImageView with a frame positioning it where you want it in the scrollview. Then you would set the UIImageView image property to the image you want. Then you would add the imageView to the scrollview as a subview.

If you need to track the imageView you should create a property for the enclosing view and assign each added imageView in turn. This way you focus specific methods on the currently selected imageView.

You do need to be aware that tracking touches in a UIScrollView can present challenges because the scrollView has to trap all touches to see if it needs to scroll.

OTHER TIPS

Matt Facer just posted a question that includes more-or-less the code you're talking about.

UIImage detecting touch and dragging

The short answer is that you don't create the UIImages in IB. You'll create the programmatically and add them to the main view as you need them. The UITouch event can be used to determine the view that was touched.

There's probably no need for an array here; an NSMutableSet makes more sense unless there's some special reason for preserving order.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top