Set an anchor point for a UIView layer

I have a subclass of UIView that I want to be able to move around inside of it. When a user touches a UIView somewhere outside self.center, but inside self.boundsit β€œskips” because I add a new location in self.centerto achieve the actual move. To avoid this behavior, I am trying to set a reference point that allows the user to capture and drag the view anywhere in its borders.

My problem is that when I calculate a new anchor point (as shown in the code below), nothing happens, the view does not change position at all. On the other hand, if I set the anchor point to a pre-calculated point, I can move the view (but then, of course, it β€œjumps” to the pre-calculated point). Why is this not working properly?

Thank.

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{
    // Only support single touches, anyObject retrieves only one touch
    UITouch *touch = [touches anyObject];
    CGPoint locationInView = [touch locationInView:self];

    // New location is somewhere within the superview
    CGPoint locationInSuperview = [touch locationInView:self.superview];

    // Set an anchorpoint that acts as starting point for the move
    // Doesn't work!
    self.layer.anchorPoint = CGPointMake(locationInView.x / self.bounds.size.width, locationInView.y / self.bounds.size.height);
    // Does work!
    self.layer.anchorPoint = CGPointMake(0.01, 0.0181818);

    // Move to new location
    self.center = locationInSuperview;
}
+5
source share
2 answers

, touchsBegan:withEvent:, . , anchorPoint , center, "" .

, ( center) , ( / ), center .

- :

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];
    CGPoint locationInView = [touch locationInView:self];
    CGPoint locationInSuperview = [touch locationInView:self.superview];

    self.layer.anchorPoint = CGPointMake(locationInView.x / self.frame.size.width, locationInView.y / self.frame.size.height);
    self.center = locationInSuperview;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];
    CGPoint locationInSuperview = [touch locationInView:self.superview];

    self.center = locationInSuperview;
}

anchorPoint apple docs SO, .

+12

TouchBegin. (TouchMoved), , subview .

0

All Articles