I wanted to create a draggable view which has many action elements. To accomplish this I replicated the code through Apple Documentation for creating a draggable view from here.
The view gets panned as expected but when an action element is clicked the view shifts to some other location. Here is the sample code and a screenshot of Main.storyboard to replicate the issue.
ViewController.h file
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
- (IBAction)segmentedAction:(id)sender;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentOutlet;
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
And this is the code in the ViewController.m file
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
UIView *piece = gestureRecognizer.view;
CGPoint locationInView = [gestureRecognizer locationInView:piece];
CGPoint locationInSuperview = [gestureRecognizer locationInView:piece.superview];
piece.layer.anchorPoint = CGPointMake(locationInView.x / piece.bounds.size.width, locationInView.y / piece.bounds.size.height);
piece.center = locationInSuperview;
}
}
- (IBAction)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
UIView *piece = [gestureRecognizer view];
[self adjustAnchorPointForGestureRecognizer:gestureRecognizer];
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
CGPoint translation = [gestureRecognizer translationInView:self.view];
[piece setCenter:CGPointMake([piece center].x + translation.x, [piece center].y + translation.y)];
[gestureRecognizer setTranslation:CGPointZero inView:self.view];
}
}
- (IBAction)segmentedAction:(id)sender {
self.label.text = [NSString stringWithFormat:@"%ld",self.segmentOutlet.selectedSegmentIndex];
}
@end
Can anybody guide me as to what I'm doing wrong here.
Thanks in advance
0 comments:
Post a Comment