I need to drag my UIView object. I use this code, but it does not work
float oldX, oldY;
BOOL dragging;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self];
if ([[touch.view class] isSubclassOfClass:[UILabel class]]) {
UILabel *label = (UILabel *)touch.view;
if (CGRectContainsPoint(label.frame, touchLocation)) {
dragging = YES;
oldX = touchLocation.x;
oldY = touchLocation.y;
}
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
dragging = NO;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self];
if ([[touch.view class] isSubclassOfClass:[UILabel class]]) {
UILabel *label = (UILabel *)touch.view;
if (dragging) {
CGRect frame = label.frame;
frame.origin.x = label.frame.origin.x + touchLocation.x - oldX;
frame.origin.y = label.frame.origin.y + touchLocation.y - oldY;
label.frame = frame;
}
}
}
With this code i could move my UIView Object anywhere. My ViewController.swift looks like this.
Hope it helps although it is another way to do it than the one mentioned in question.
This is work code for move UIView objects
float oldX, oldY; BOOL dragging;
I would suggest using a
UIPanGestureRecognizer
:This is just a preference of mine. To me it is a lot simpler using a gesture recognizer then using
touchesBegan
,touchesEnded
,touchesMoved
. I will use these in cases where theUIPanGestureRecognizer
will not work.There's something a bit strange in your code.
You ask for the location in
self
, some UIView which presumably contains theUILabel
you want to check. This begs the question as to why you do not add the touchesXXX to some UILabel subclass of yours.This cancels out as you're using the label.frame which is defined in terms of its superview.bounds (your parent UIView you asked the touch location with respect to), but this doesn't make for the most straightforward way to follow what's going on.