I have around 16 UIImage views, can be moved by touch. I can drop over UIImage over another UIImage and then the UIImages would exchange their position. Being newcomer to ObjectiveC programming, I am struggling to figure out the UIImageViews and exchange their positons. Till now I am trying to implement in touchesEnded method
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
[self.superview exchangeSubviewAtIndex:[[self.superview subviews] indexOfObject:self] withSubviewAtIndex:[[self.superview subviews] indexOfObject:[touch view]]];
}
But this does not work. Any help would be appreciated.
UIImages are created by following code
TouchImageView *touchImageView = [[TouchImageView alloc]initWithImage:displayImage];
touchImageView.identy = [NSString stringWithFormat:@"Image ID %d",i];
So each touch image is associated some string to describe itself.
In touch end, I have just added following code to know ID of image views
UITouch *touch = [touches anyObject];
TouchImageView *dragImage = (TouchImageView*)[touch view];
NSLog(@"Ended %a%a",[dragImage identy],[self identy]);
But the o/p I got is totally different
2011-11-21 11:50:34.404 OrganizeMe[882:f803] Ended 0x1.6d96006a6d96p-9170x1.807p-1022
FInal code
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
__block int tag = -1;
__block float distance = 100000.0;
[[self.superview subviews] enumerateObjectsUsingBlock:^(UIView *view, NSUInteger index, BOOL *stop) {
BOOL interSect = CGRectIntersectsRect([self frame], [view frame]);
if(interSect && ([self tag]!=[view tag])){
[self.image CGImage];
CGPoint currPoint = [[touches anyObject]locationInView:[self superview]];
CGPoint underPoint = view.center;
if(distance >= [self distanceBetweenPoint1:currPoint Point2:underPoint]){
distance = [self distanceBetweenPoint1:currPoint Point2:underPoint] ;
tag = [view tag];
}
}
}];
NSLog(@"Tag and Distance %d,%f",tag,distance);
TouchImageView* imageView1 = (TouchImageView*)[self.superview viewWithTag:tag];
CGRect point1 = [imageView1 frame];
CGRect point2 = [self frame];
if(tag != -1){
[imageView1 setFrame:point2];
[self setFrame:point1];
}else{
CGPoint lastTouch = [[touches anyObject]previousLocationInView:[self superview]];
self.center = lastTouch;
}
[self.superview setNeedsLayout];
}
The index is just the UIView’s position in the subview array. It does not set the location within the superview.
Relayout the superview based on the subview’s index.
In your above method, also call
setNeedsLayoutin order to relayout the superview.Implement the following method for the superview:
It’s been a long time I last used Cocoa touch, so I can’t guarantee that the code is working.