This is my code:
- (void) touchesBegan: (NSSet *)touches withEvent: (UIEvent *)event {
CGPoint pt = [[touches anyObject] locationInView:self.view];
startLocation = pt;
[super touchesBegan: touches withEvent: event];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint pt开发者_C百科 = [[touches anyObject] locationInView:self.view];
CGRect frame = [self.view frame];
frame.origin.x += pt.x - startLocation.x;
frame.origin.y += pt.y - startLocation.y;
[self.view setFrame:frame];
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIView *v = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 100, 100)];
v.backgroundColor = [UIColor redColor];
UIImageView *imv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"boo2.png"]];
imv.frame = CGRectMake(0, 0, 50, 50);
[v addSubview:imv];
[self.view addSubview: v];
[v release];
UIView *v2 = [[UIView alloc] initWithFrame: CGRectMake(100, 100, 100, 100)];
v2.backgroundColor = [UIColor blueColor];
UIImageView *imv2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"boo2.png"]];
imv2.frame = CGRectMake(0, 0, 50, 50);
[v2 addSubview:imv2];
[self.view addSubview: v2];
[v2 release];
}
What I want to do is to move the UIImageView inside the UIView, not the entire view. But, the code above, when I try to drag, it moves the entire view.
NOTE: The images are return from others functions, not declared in viewdidload. Assume, you cant declare UIImageView variables.
I'm not quite sure what you're trying to do. and I don't know why you put each of the UIImageView's
inside a UIView
which you put into the view controller's view. You can just as well add the UIImageView's
as sub-views of the view controller's view directly.
Nevertheless, from what I can make out it looks like the user must be able to drag the images on the screen around.
If this is the case, I would suggest that you store each one of the UIImageView's
in an array. Then, in touchesBegan:withEvent:
, you will have to determine which UIImageView
is being touched. Getting the CGPoint
representing the location in the main view, as you do in your code, is a good start. If you added the UIImageView's
directly as sub-views of the main view, you can then compare the coordinates of this CGPoint
with the frames of these UIImageView's
to determine which one is being pressed.
Then, to allow dragging, you need to save the coordinates of the UIImageView
at the beginning of the touch. Then, everytime the touch moves, you can compute the new x-position of the UIImageView
as the original x-position, plus the distance moved. That is,
newImageViewX = imageViewStartX + (newTouchX - touchStartX);
and similarly for the y-position.
精彩评论