使用UIPanGestureRecognizer在可拖动视图中的操作元素会导致视图移动

时间:2015-04-08 10:12:08

标签: ios objective-c iphone uisegmentedcontrol uipangesturerecognizer

我想创建一个具有许多动作元素的可拖动视图。为此,我通过Apple文档复制了代码,以便从here创建可拖动的视图。

视图按预期平移,但是当单击一个动作元素时,视图会转移到其他位置。以下是用于复制问题的示例代码和Main.storyboard的屏幕截图。

Main.storyboard

ViewController.h文件

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

- (IBAction)segmentedAction:(id)sender;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentOutlet;
@property (weak, nonatomic) IBOutlet UILabel *label;

@end

这是ViewController.m文件中的代码

#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

任何人都可以指导我在这里做错了什么。

提前致谢

1 个答案:

答案 0 :(得分:1)

好的,终于得到了问题。由于Autolayout,这种情况正在发生。当您尝试设置标签的文本时,autolayout强制视图框重置为初始值。由于您更改了锚点,因此它似乎会移动到某个随机位置。

要解决此问题,只需在viewDidLoad方法中使用以下行;

self.label.translatesAutoresizingMaskIntoConstraints = YES;

或者在UIView *piece = gestureRecognizer.view;方法中添加以下adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer行: -

piece.translatesAutoresizingMaskIntoConstraints = YES;

干杯: - )