UIDynamicAnimator / UIAttachmentBehavior嘻嘻哈哈?

时间:2014-04-16 02:00:20

标签: ios uidynamicanimator

使用Xcode 5.1.1在iOS7中使用新的物理引擎时,我编写了以下代码:

#import "ZViewController.h"

@interface ZViewController ()
@property (nonatomic, strong) UIView *cardView;
@property (nonatomic, strong) UIDynamicAnimator *animator;
@property (nonatomic, strong) UIAttachmentBehavior *attachment;
@end

@implementation ZViewController

- (void)viewDidLoad{
    [super viewDidLoad];

    self.cardView = [[UIView alloc]initWithFrame:CGRectMake(0.0, 0.0, 100.0, 100.0)];
    self.cardView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:self.cardView];

    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGestureHandler:)];
    [self.cardView addGestureRecognizer:panGestureRecognizer];

    self.animator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    self.cardView.center = self.view.center;
}

- (void)panGestureHandler:(UIPanGestureRecognizer *)panGesture{
    CGPoint touchPoint = [panGesture locationInView:self.view];
    switch(panGesture.state){
        case UIGestureRecognizerStateBegan:
            self.attachment = [[UIAttachmentBehavior alloc]initWithItem:self.cardView attachedToAnchor:touchPoint];
            [self.animator addBehavior:self.attachment];
            break;
        case UIGestureRecognizerStateChanged:
            touchPoint.x = 160.0;
            self.attachment.anchorPoint = touchPoint;
            break;
        case UIGestureRecognizerStateEnded:
            [self.animator removeBehavior:self.attachment];
            self.attachment = nil;
            break;
        default:
            break;
    }
}

@end

当我测试这段代码时,我发现了一个非常奇怪的摆动/摇晃。大多数情况下,向上和向下拖动cardView可以完成预期的操作,即cardView以x轴为中心向上和向下滑动,但卡片视图通常对角线向左移动,对角线向后移动到x轴中心。这种摆动似乎并不一致,但似乎总是向左摆动。

有没有人见过这个?任何想法是什么原因导致的怎么阻止它?

提前致谢 - AYAL

1 个答案:

答案 0 :(得分:2)

我尝试了您的代码并可以复制该问题。在设定长度后,它停止了问题。

尝试将附件的长度设置为1

case UIGestureRecognizerStateBegan:
     self.attachment = [[UIAttachmentBehavior alloc]initWithItem:self.cardView attachedToAnchor:touchPoint];
     self.attachment.length = 1;
     [self.animator addBehavior:self.attachment];
     break;