I have 2 images in a view and I applied a drag touch function to the images, and when the image collides with the image at the top of the view it gives you an alert and changes the image at the top of the view to a different image.
My problem is getting my if else statement to work, If i take out the == image in
([touch view] == image) {
Only one of the images drag, I cannot seem to get both images to drag. My if else statement has no errors, but does not seem to work.
frfViewController.h
#import <UIKit/UIKit.h>
#interface frfViewController : UIViewController {
UIImageView *image;
UIImageView *image2;
UIImageView *images;
UIImageView *collisionImage;
}
#property (nonatomic, retain) IBOutlet UIImageView *image;
#property (nonatomic, retain) IBOutlet UIImageView *image2;
#property (nonatomic, retain) IBOutlet UIImageView *collisionImage;
#property (nonatomic, retain) IBOutlet UIImageView *images;
#end
frfViewController.m
#import "frfViewController.h"
#interface frfViewController ()
#end
#implementation frfViewController
#synthesize image;
#synthesize image2;
#synthesize images;
#synthesize collisionImage;
- (void)viewDidLoad
{
}
- (void)viewWillAppear:(BOOL)animated
{
// [self.navigationController setNavigationBarHidden:YES animated:animated];
// [super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[self.navigationController setNavigationBarHidden:NO animated:animated];
[super viewWillDisappear:animated];
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:self.view];
if ([touch view] == image) {
image.center = location;
image.userInteractionEnabled = YES;
}
else if ([touch view] == image2) {
image2.center = location;
image2.userInteractionEnabled = YES;
}
[self ifCollided];
}
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[self touchesBegan:touches withEvent:event];
}
-(void) ifCollided {
if (CGRectIntersectsRect(image.frame, collisionImage.frame) || CGRectIntersectsRect(image2.frame, collisionImage.frame)) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"image Collided"
message:#"FuckYea"
delegate:nil
cancelButtonTitle:#"Reset!"
otherButtonTitles:nil];
[alert show];
CGRect myImageRect = CGRectMake(0, 0, 320, 100);
images = [[UIImageView alloc] initWithFrame:myImageRect];
[images setImage:[UIImage imageNamed:#"004.jpg"]];
[self.view addSubview:images];
}
}
#end
Thanks any assistance is much appreciated.
From iOS 4 and up you can use UIPanGestureRecognizer to do dragging easily,
UIPanGestureRecognizer *gesture = [[UIPanGestureRecognizer alloc]
initWithTarget:self
action:#selector(labelDragged:)];
[yourview addGestureRecognizer:gesture];
Add recognizer to each UIView and set selector to point, where you set new coordinates = where you can limit it , if you get collision for example...
- (void)labelDragged:(UIPanGestureRecognizer *)gesture
{
UILabel *label = (UILabel *)gesture.view;
CGPoint translation = [gesture translationInView:label];
// move label , limit it to stay inside self.view.frame
float newx = label.center.x + translation.x;
float newy = label.center.y + translation.y;
if (newx<0) { newx = 0; }
if (newy<0) { newy = 0; }
if (newx>self.view.frame.size.width) {
newx = self.view.frame.size.width;
}
if (newy>self.view.frame.size.height) {
newy = self.view.frame.size.height;
}
//possibly compute collision here and limit new coordinates further
label.center = CGPointMake(newx,newy);
// reset translation
[gesture setTranslation:CGPointZero inView:label];
}
Also have a look at draggable&resizable View class at https://github.com/spoletto/SPUserResizableView , that may save you a bit of work also
Related
I am getting an error in my project. I have tried plenty of solutions but to no avail.
I am getting an error Xcode Error Semantic error value may not respond to 'initWithFrame:image Name:'
I have no idea what this means and why i'm getting this warning. Please help.
Thanks
Link to my project and the Updated project link.
I'm getting the error in this line
GalleryButton *btnAttachment = [[GalleryButton alloc] initWithFrame:CGRectMake(startX, startY, width, height) imageName:imgName];
GalleryScrollView.h
#import <UIKit/UIKit.h>
#import "AttachmentItem.h"
#import "GalleryButton.h"
#protocol GAlleryScrollDelegate;
#interface GalleryScrollView : UIView <GalleryButtonDelegate>
{
id <GAlleryScrollDelegate> delegate;
// MAIN WINDOW WHERE YOU CAN DRAG ICONS
UIView *mainView;
UIScrollView *_scrollView;
NSMutableArray *_attachments;
NSInteger *_totalSize;
UIImageView *_recycleBin;
CGRect recycleBinFrame;
}
#property (nonatomic, retain) id <GAlleryScrollDelegate> delegate;
#property (nonatomic, retain) UIView *mainView;
#property (nonatomic, retain) NSMutableArray *attachments;
#property (nonatomic, retain) UIImageView *recycleBin;
#property (nonatomic, retain) UIImageView *imgName;
#property (nonatomic) CGRect recycleBinFrame;
- (void) addAttachment:(AttachmentItem *)attachment withImageNamed:(NSString *)imgName;
- (void) removeAttachment:(GalleryButton *)button;
- (void) reloadData;
- (id) initWithFrame:(CGRect)frame imageName:(NSString *)imageName;
#end
// EVENTS IF YOU WANT TO DISABLE SOME SCROLL ON DID PRESS AND ENABLE IT ON DROP
#protocol GAlleryScrollDelegate
- (void) didPressButton;
- (void) didDropButton;
#end
GalleryScrollView.m
#import <QuartzCore/QuartzCore.h>
#import "GalleryScrollView.h"
#import "GalleryButton.h"
#implementation GalleryScrollView
#synthesize delegate;
#synthesize mainView;
#synthesize attachments = _attachments;
#synthesize recycleBin = _recycleBin, recycleBinFrame;
int padding = 0;
#pragma mark - INIT
- (id) init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
- (id) initWithFrame:(CGRect)frame imageName:(NSString *)imageName
{
self = [super initWithFrame:frame];
if (self){
;
}
return self;
}
- (void) awakeFromNib
{
// INIT ATTACHMENT ARRAY
if (_attachments == nil){
_attachments = [[NSMutableArray alloc] init];
}
// SCROLL VIEW
UIScrollView *scrollTemp = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width-0, 450)];
_scrollView = scrollTemp;
_scrollView.backgroundColor = [UIColor clearColor];
// RECYCLE BIN
UIImageView *imageViewTemp = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"mozambique-wenge.png"]];
self.recycleBin = imageViewTemp;
self.recycleBin.frame = CGRectMake(0, 0, 320, 270);
[self addSubview:_scrollView];
[self addSubview:self.recycleBin];
[scrollTemp release];
[imageViewTemp release];
}
- (void) dealloc {
[super dealloc];
}
#pragma mark - ATTACHMENTS ADD / REMOVE
- (void) addAttachment:(AttachmentItem *)attachment withImageNamed:(NSString *)imgName
{
// SAVE ATTACHMENT
[_attachments addObject:attachment];
// RESIZE CONTENT VIEW FOR INSERTINT NEW ATTACHMENT
_scrollView.contentSize = CGSizeMake([_attachments count]*70, 70);
CGFloat startX = (70.0f * ((float)[_attachments count] - 1.0f) + padding);
CGFloat startY = 370;
CGFloat width = 64;
CGFloat height = 64;
GalleryButton *btnAttachment = [[GalleryButton alloc] initWithFrame:CGRectMake(startX, startY, width, height) imageName:imgName];
btnAttachment.tag = [_attachments count];
btnAttachment.scrollParent = _scrollView;
btnAttachment.mainView = self.mainView;
btnAttachment.delegate = self;
if (attachment.type == 1){
}else if (attachment.type == 2){
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 64, 64)];
imageView.image=[UIImage imageNamed:#"mozambique-wenge"];
[btnAttachment addSubview:imageView];
[imageView release];
} else if (attachment.type == 3){
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 64, 64)];
imageView.image=[UIImage imageNamed:#"recyclebin.png"];
[btnAttachment addSubview:imageView];
[imageView release];
}
[_scrollView addSubview:btnAttachment];
[btnAttachment release];
}
- (void) removeAttachment:(GalleryButton *)button
{
}
#pragma mark - RELOAD DATA
- (void) reloadData
{
}
#pragma mark - GALLERY BUTTON DELEGATE
-(void) touchDown
{
[self.delegate didPressButton];
}
-(void) touchUp
{
[self.delegate didDropButton];
_scrollView.scrollEnabled = YES;
}
-(BOOL) isInsideRecycleBin:(GalleryButton *)button touching:(BOOL)finished;
{
CGPoint newLoc = [self convertPoint:self.recycleBin.frame.origin toView:self.mainView];
CGRect binFrame = self.recycleBin.frame;
binFrame.origin = newLoc;
if (CGRectIntersectsRect(binFrame, button.frame) == TRUE){
if (finished){
[self removeAttachment:button];
}
return YES;
}
else {
return NO;
}
}
#end
GalleryButton.h
#import <UIKit/UIKit.h>
#protocol GalleryButtonDelegate;
#interface GalleryButton : UIView
{
id<GalleryButtonDelegate> delegate;
CGPoint _originalPosition;
CGPoint _originalOutsidePosition;
BOOL isInScrollview;
// PARENT VIEW WHERE THE VIEWS CAN BE DRAGGED
UIView *mainView;
// SCROLL VIEW WHERE YOU GONNA PUT THE THUMBNAILS
UIScrollView *scrollParent;
UIImageView *images;
}
#property (nonatomic, retain) id<GalleryButtonDelegate> delegate;
#property (nonatomic) CGPoint originalPosition;
#property (nonatomic, retain) UIView *mainView;
#property (nonatomic, retain) UIScrollView *scrollParent;
#property (nonatomic, retain) IBOutlet UIImageView *images;
#end
#protocol GalleryButtonDelegate
-(void) touchDown;
-(void) touchUp;
-(BOOL) isInsideRecycleBin:(GalleryButton *)button touching:(BOOL)finished;
#end
GalleryButton.m
#import <QuartzCore/QuartzCore.h>
#import "GalleryButton.h"
#import "GalleryScrollView.h"
#import "AttachmentItem.h"
#implementation GalleryButton
#synthesize delegate;
#synthesize originalPosition = _originalPosition;
#synthesize mainView, scrollParent;
#synthesize images;
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self){
isInScrollview = YES;
self.backgroundColor = [UIColor blackColor];
self.layer.borderWidth = 2;
self.layer.borderColor = [UIColor blackColor].CGColor;
self.layer.masksToBounds = YES;
self.layer.cornerRadius = 5;
}
return self;
}
#pragma mark - DRAG AND DROP
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.delegate touchDown];
self.originalPosition = self.center;
self.scrollParent.scrollEnabled = NO;
if (isInScrollview == YES) {
CGPoint newLoc = CGPointZero;
newLoc = [[self superview] convertPoint:self.center toView:self.mainView];
_originalOutsidePosition = newLoc;
// [self.superview touchesCancelled:touches withEvent:event];
[self removeFromSuperview];
self.center = newLoc;
[self.mainView addSubview:self];
[self.mainView bringSubviewToFront:self];
isInScrollview = NO;
}
else {
;
}
}
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[UIView beginAnimations:#"stalk" context:nil];
[UIView setAnimationDuration:.001];
[UIView setAnimationBeginsFromCurrentState:YES];
UITouch *touch = [touches anyObject];
self.center = [touch locationInView: self.superview];
[UIView commitAnimations];
if ([delegate isInsideRecycleBin:self touching:NO]){
}
}
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if ([delegate isInsideRecycleBin:self touching:YES]){
CGRect myImageRect = CGRectMake(0, 0, 320, 300);
images = [[UIImageView alloc] initWithFrame:myImageRect];
[images setImage:[UIImage imageNamed:#"light-cherry.png"]];
[self.mainView addSubview:images];
[self.images viewWithTag:1];
UIImageView * animation = [[UIImageView alloc] init];
animation.frame = CGRectMake(self.center.x - 32, self.center.y - 32, 40, 40);
animation.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed: #"iconEliminateItem1.png"],
[UIImage imageNamed: #"iconEliminateItem2.png"],
[UIImage imageNamed: #"iconEliminateItem3.png"],
[UIImage imageNamed: #"iconEliminateItem4.png"]
,nil];
[animation setAnimationRepeatCount:1];
[animation setAnimationDuration:0.35];
[animation startAnimating];
[self.mainView addSubview:animation];
[animation bringSubviewToFront:self.mainView];
[animation release];
;
[UIView beginAnimations:#"goback" context:nil];
[UIView setAnimationDuration:0.4f];
[UIView setAnimationBeginsFromCurrentState:YES];
self.center = _originalOutsidePosition;
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector: #selector(animationDidStop:finished:context:)];
// loadingView.frame = CGRectMake(rect.origin.x, rect.origin.y - 80, rect.size.width, rect.size.height);
[UIView commitAnimations];
} else{
[UIView beginAnimations:#"goback" context:nil];
[UIView setAnimationDuration:0.4f];
[UIView setAnimationBeginsFromCurrentState:YES];
self.center = _originalOutsidePosition;
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector: #selector(animationDidStop:finished:context:)];
// loadingView.frame = CGRectMake(rect.origin.x, rect.origin.y - 80, rect.size.width, rect.size.height);
[UIView commitAnimations];
}
[self.delegate touchUp];
}
-(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
if ([animationID isEqualToString:#"goback"] && finished) {
[self removeFromSuperview];
self.center = _originalPosition;
[self.scrollParent addSubview:self];
isInScrollview = YES;
}
}
#end
The problem is that you haven't declared the custom init method:
- (id)initWithFrame:(CGRect)frame imageName:(NSString *)imageName;
In GalleryButton.h. You also haven't implemented it in GalleryButton.m. Perhaps you didn't mean to use this method at all in your code?
Either way you've referenced it and Xcode has correctly warned you that it doesn't exist (if you build and run the code you will get an Unrecognized selector sent to instance exception).
You need to place initWithFrame:image Name in GalleryButton in its header file. Always remember, if you get a warning that's says something like "May not respond to..." It's because it's not publicly mentioned in the classes header file.
Okay. After killing myself trying I found my mistake.
I Used:
- (id)initWithFrame:(CGRect)frame imageName:(NSString *)imageName;
In both the GalleryButton.h and GalleryScrollview.h and I just took it out of GalleryScrollview.h
Thanks All
I'm actually trying to insert touch delegate functions (type touchBegan:withEvent, or touchEnded:withEvent) inside a customScrollView class that implement gestureRecognizers.
When I try to set the delegate of the recognizer object to self, my SDK has a message of warning stating "incompatible type id ".
I understand that the delegate protocol of GestureRecognizer does not include such function, but I don't know which delegate I should trigger in order to use the aforesaid function inside my custom view.
Thank you very much for your responses
Victor-Marie
Here is my code:
#interface TapScrollView : UIScrollView {
// id<TapScrollViewDelegate> delegate;
NSMutableArray *classementBoutons;
int n;
int o;
//UIImageView *bouton;
}
//#property (nonatomic, assign) id<TapScrollViewDelegate> delegate;
//#property (nonatomic, retain) UIImageView *bouton;
//#property (strong, nonatomic) UIPanGestureRecognizer *bouton01pan;
-(id)init;
-(void)initierScrollView;
-(void) createGestureRecognizers;
-(IBAction)handlePanGesture:(UIPanGestureRecognizer*)sender;
#end
#import "TapScrollView.h"
#implementation TapScrollView
//#synthesize bouton;
- (void)setUpBoutonView {
// Create the placard view -- its init method calculates its frame based on its image
//boutonHome *aBoutonMain = [[boutonHome alloc] init];
//self.boutonMain = aBoutonMain;
//[boutonMain setCenter:CGPointMake(200, 200)];
//[self addSubview:boutonMain];
}
- (id) init
{
if (self = [super init])
{
NSLog(#"Classe TapScrollView initiée");
}
return self;
}
-(void)initierScrollView
{
int i;
for (i=0; i<6; i++) {
UIImage *image = [UIImage imageNamed:#"back.png"];
UIImageView *bouton = [[UIImageView alloc] initWithImage:image];
[bouton setTag:i];
[bouton setFrame:CGRectMake(72+20*i,10,62,55)];
[classementBoutons insertObject:bouton atIndex:i];
bouton.userInteractionEnabled = YES;
UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(handlePanGesture:)];
recognizer.delegate = self;
[bouton addGestureRecognizer:recognizer];
[self addSubview:bouton];
}
}
//- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//{
// UITouch *touch = [touches anyObject];
//[super touchesBegan:touches withEvent:event];
// for (o=1; o<6; o++) {
// if ([touch view] == [self viewWithTag:o])
// {
// UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:[classementBoutons objectAtIndex:o] action:#selector(handlePanGesture:)];
// [[classementBoutons objectAtIndex:o] addGestureRecognizer:recognizer];
// bouton01 = [self viewWithTag:o];
// }
// }
//CGPoint touchPoint = [touch locationInView:self];
//[self animateFirstTouchAtPoint:touchPoint];
// return;
//}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
for (n=0; n<6; n++) {
NSLog(#"touche cancelled");
[[classementBoutons objectAtIndex:n] setFrame:CGRectMake((72+20)*n,10,62,55)];
}
}
//- (id<TapScrollViewDelegate>) delegate {
// return (id<TapScrollViewDelegate>)super.delegate;
//}
//- (void) setDelegate:(id<TapScrollViewDelegate>) aDelegate
//{
// super.delegate = aDelegate;
//}
#define GROW_ANIMATION_DURATION_SECONDS 0.15
#define SHRINK_ANIMATION_DURATION_SECONDS 0.15
-(IBAction)handlePanGesture:(UIPanGestureRecognizer*)recognizer
{
NSLog(#"Mouvement ok");
CGPoint translation = [recognizer translationInView:self];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self];
}
#end
Try specifying:
#interface TapScrollView : UIScrollView <UIGestureRecognizerDelegate> {
In this way, your warning should disappear, although I have to admit I have not entirely clear what you are trying to accomplish, so there might be other problems.
I,
I'm currently trying to implement a Gesture recognizer into a ScrollView.
I first created a custom ScrollView in which I integrated ImageView object.
When the user clicks on a ImageView, normally the PanGestureRecognizer activates and the ImageView object follow the move on the screen.
I have read and followed the instructions on Gesture Recognizer and the Raywenderlich blog (which is very well done).
If someone has a clue of what is missing in my code, I would be happy to read it
Thank in advance. Here is my code
#import <Foundation/Foundation.h>
#import "mainInterface03.h"
#import <QuartzCore/QuartzCore.h>
#import "boutonHome.h"
#import "DragGestureRecognizer.h"
#class boutonHome;
#class DragGestureRecognizer;
#interface TapScrollView : UIScrollView {
// id<TapScrollViewDelegate> delegate;
NSMutableArray *classementBoutons;
int n;
int o;
UIView *bouton01;
}
#property (nonatomic, retain) UIView *bouton01;
#property (retain, nonatomic) IBOutletCollection(UIButton) NSMutableSet* buttons;
-(id)init;
-(void)initierScrollView;
-(void) createGestureRecognizers;
-(IBAction)handlePanGesture:(UIPanGestureRecognizer*)sender;
#end
m.file
#import "TapScrollView.h"
#implementation TapScrollView
#synthesize bouton01;
- (id) init
{
if (self = [super init])
{
NSLog(#"Classe TapScrollView initiée");
}
return self;
}
-(void)initierScrollView
{
int i;
for (i=0; i<6; i++) {
UIImage *image = [UIImage imageNamed:#"back.png"];
UIImageView *bouton = [[UIImageView alloc] initWithImage:image];
[bouton setTag:i];
[bouton setFrame:CGRectMake(72*i+20,10,62,55)];
[classementBoutons insertObject:bouton atIndex:i];
[self addSubview:bouton];
}
UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:bouton01 action:#selector(handlePanGesture:)];
[bouton01 addGestureRecognizer:recognizer];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
[super touchesBegan:touches withEvent:event];
for (o=1; o<6; o++) {
if ([touch view] == [self viewWithTag:o])
{
bouton01 = [self viewWithTag:o];
}
}
return;
}
-(IBAction)handlePanGesture:(UIPanGestureRecognizer*)recognizer
{
NSLog(#"Mouvement ok");
CGPoint translation = [recognizer translationInView:self];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self];
}
#end
I am not sure if this setup can work. Essentially, you are assigning whatever view has been touched to bouton01, which carries the gesture recognizer. Seems a bit convoluted to me, and also your code is not so efficient.
It seems that when you call [super touchesBegan:touches withEvent:event]; it will pass the touch up the view hierarchy. Only after that do make the assignment to bouton01. So it would seem logical that bouton01 never receives a touch event.
Indeed, it is because of this strange approach of iterating through the views and assigning it the one that has the recognizer that this error arose. I would suggest to assign the same recognizer to all concerned views during setup.
I want to make a app where I need to have a toolbar. The toolbar will have various number of objects (images). These objects should be draggable and placed on view right above it.
This is a kind of drawing app where user can pick any shape and place on canvas. Can anyone tell me the best to achieve this ?
Thanks in advance.
Tough one.
What I would do is make each item on the toolbar a UIView and override touchesBegan, touchesEnded, and touchesMoved. Make your canvas another UIView. When a user clicks an item to drag, register that item somewhere, say a square. then when they drop on the canvas, draw that square at that location. To make it look pretty, would probably make a UIImageView with an alpha of like .4 to move with the user's touch, so they know what they are dragging, and where it will land.
Here is the code.
UIViewController.h
#class ToolBox;
#interface ViewController : UIViewController {
IBOutlet UIView *canvas;
IBOutlet ToolBox *toolBox;
}
#property (nonatomic, retain) UIView *canvas;
#property (nonatomic, retain) ToolBox *toolBox;
#end
UIViewController.m
#import "ViewController.h"
#import "ToolBox.h"
#import "Tool.h"
#implementation ViewController
#synthesize canvas, toolBox;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[self toolBox] setCanvas:[self canvas]];
Tool *tool = [[[Tool alloc] initWithFrame:CGRectMake(0,0,64,64)] autorelease];
[tool setImageView:[[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"1.png"]] autorelease]];
[tool setImage:[UIImage imageNamed:#"1.png"]];
[tool addSubview:[tool imageView]];
[tool setToolBox:[self toolBox]];
[[self toolBox] addObject:tool];
}
#end
ToolBox.h
#class Tool;
#interface ToolBox : UIView {
NSMutableArray *tools;
UIView *canvas;
UIImage *currentTool;
}
#property (nonatomic, retain) UIImage *currentTool;
#property (nonatomic, retain) NSMutableArray *tools;
#property (nonatomic, retain) UIView *canvas;
-(void)addObject:(Tool *)newTool;
-(void)updatePositions;
#end
ToolBox.m
#implementation ToolBox
#synthesize tools, canvas, currentTool;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
-(void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
-(NSMutableArray *)tools {
if(tools == nil) {
[self setTools:[NSMutableArray array]];
}
return tools;
}
-(void)addObject:(Tool *)newTool {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(draggingTool:) name:#"Dragging New Tool" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(draggedTool:) name:#"Dragged Tool To" object:nil];
[[self tools] addObject:newTool];
[self updatePositions];
}
-(void)updatePositions {
int x = 0;
int y = 0;
int width = 64;
int height = 64;
for(Tool *button in [self tools]) {
[button setFrame:CGRectMake(x, y, width, height)];
x += width;
[self addSubview:button];
}
}
-(void)draggingTool:(NSNotification *)notif {
NSDictionary *dict = [notif userInfo];
UIImage *image = [dict valueForKey:#"Image"];
[self setCurrentTool:image];
}
-(void)draggedTool:(NSNotification *)notif {
UITouch *touch = [[notif userInfo] valueForKey:#"Touch"];
CGPoint point = [touch locationInView:canvas];
UIImageView *imageView = [[[UIImageView alloc] initWithImage:currentTool] autorelease];
[imageView setCenter:point];
[canvas addSubview:imageView];
}
#end
Tool.h
#class ToolBox;
#interface Tool : UIView {
UIImageView *imageView;
UIImage *image;
UIImageView *ghostImageView;
ToolBox *toolBox;
}
#property (nonatomic, retain) UIImageView *imageView;
#property (nonatomic, retain) UIImage *image;
#property (nonatomic, retain) UIImageView *ghostImageView;
#property (nonatomic, retain) ToolBox *toolBox;
#end
Tool.m
#import "Tool.h"
#import "ToolBox.h"
#implementation Tool
#synthesize imageView, image, ghostImageView, toolBox;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(#"tool touches began");
NSDictionary *dict = [NSDictionary dictionaryWithObject:[self image] forKey:#"Image"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"Dragging New Tool" object:nil userInfo:dict];
UITouch *touch = [touches anyObject];
CGPoint center = [touch locationInView:[[self toolBox] canvas]];
[self setGhostImageView:[[[UIImageView alloc] initWithImage:[self image]] autorelease]];
[[self ghostImageView] setCenter:center];
[[[self toolBox] canvas] addSubview:[self ghostImageView]];
[[self ghostImageView] setAlpha:.4];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(#"tool touches ended");
NSDictionary *dict = [NSDictionary dictionaryWithObject:[touches anyObject] forKey:#"Touch"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"Dragged Tool To" object:nil userInfo:dict];
[self setGhostImageView:nil];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(#"tool touch moved");
if([self ghostImageView] != nil) {
UITouch *touch = [touches anyObject];
CGPoint center = [touch locationInView:[[self toolBox] canvas]];
NSLog(#"Ghost : %2f, %2f", center.x, center.y);
[[self ghostImageView] setCenter:center];
}
}
#end
My Program came out like this -
Initial screen: The tool is ready to be dragged and dropped onto the canvas
Dropped the tool on the canvas
And here is the ghost for the transition
I'm not exactly sure how this would be implemented in objective c, but I have done almost exactly what you are describing in java. Basically, when you begin to drag the object in the toolbar, it will recognize the action and store a new instance of the item in what I call a transfer container, which is basically a global static variable. That way when the drag action competes (I.e. drops) you can just grab that object from the container and add it to wherever it was dropped.
I have a problem with touchesBegan event.I displayed an image in an uiimageview.Am trying to detect the touches on that image by displaying small green color points on the image when i clicked on the image..
Am not getting any errors while running but the touches event is not firing.Here is my code:
#import <UIKit/UIKit.h>
#import "Second.h"
#interface pickerExampleViewController : UIViewController <UIImagePickerControllerDelegate>{
IBOutlet UIButton *selectPic;
}
#property (nonatomic,retain) UIButton *selectPic;
-(IBAction)getpic:(id)sender;
#end
#import "pickerExampleViewController.h"
#implementation pickerExampleViewController
#synthesize selectPic;
-(IBAction)getpic:(id)sender
{
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
picker.editing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentModalViewController:picker animated:YES];
[picker release];
}
#pragma mark imagePickerController delegate methods
-(void)imagePickerController:(UIImagePickerController *) picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
[picker dismissModalViewControllerAnimated:YES];
Second *secview = [[Second alloc] initWithNibName:#"Second" bundle:nil];
secview.view.backgroundColor = [UIColor blackColor];
[secview setImage:image];
[self.view addSubview:secview.view];
//[self presentModalViewController:secview animated:YES];
[secview release];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissModalViewControllerAnimated:YES];
}
#interface Second : UIViewController {
IBOutlet UIImageView *imgView;
UIImage *image1;
}
#property(nonatomic,retain) UIImageView *imgView;
-(void)setImage:(UIImage *)img;
-(IBAction)back;
#end
#import "Second.h"
#import <QuartzCore/QuartzCore.h>
#implementation Second
#synthesize imgView;
static int countoftouches,i;
CGPoint points[4];
-(void)setImage:(UIImage *)img
{
[imgView setImage:img];
countoftouches=0;
}
-(IBAction)back
{
[self.view removeFromSuperview];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
//NSSet *allTouches = [event allTouches];
if ([touch view] != imgView) {
return;
}
countoftouches++;
CGPoint point = [touch locationInView:imgView];
NSLog(#"x: %f, y: %f", point.x, point.y);
CGRect frame=CGRectMake(point.x, point.y, 5, 5);
if(countoftouches<=4)
{
points[i] = frame.origin;
i++;
UIButton *btn=[[UIButton alloc]initWithFrame:frame];
[btn setBackgroundColor:[UIColor greenColor]];
[imgView addSubview:btn];
[btn release];
}
}
-(void)dealloc
{
[imgView release];
[super dealloc];
}
#end
You need to set userInteractionEnabled to YES.. On youre UIImageView that is.. So:
imgView.userInteractionEnable = YES;