UIDynamicAnimator +自定义UICollectionViewLayout导致永久性圆周运动

问题描述:

我一直在复制2013年WWDC会话217“探索iOS 7上的滚动视图”。我使用的是Xcode 7 beta 2,我的项目只有iOS 9。UIDynamicAnimator +自定义UICollectionViewLayout导致永久性圆周运动

我正在尝试使用UIDynamicAnimator与我的UICollectionViewLayout以类似于会话217中呈现的方式来模仿Messages.app的感觉。我的UICollectionViewLayout是一个自定义的,由于某种原因,我的细胞似乎在我的项目中以圆周运动反弹。

下面是问题的video更清晰。

这是我的自定义布局代码。

// Didn't write this code myself, but should be pretty simple to follow. @Goles 


#import "VVSpringCollectionViewFlowLayout.h" 

@interface VVSpringCollectionViewFlowLayout() 
@property (nonatomic, strong) UIDynamicAnimator *animator; 
@end 

@implementation VVSpringCollectionViewFlowLayout 

-(id)init { 
    if (self = [super init]) { 
     _springDamping = 0.5; 
     _springFrequency = 0.8; 
     _resistanceFactor = 500; 
    } 
    return self; 
} 

- (id)initWithCoder:(nonnull NSCoder *)aDecoder { 
    self = [super initWithCoder:aDecoder]; 
    if (self) { 
     _springDamping = 0.5; 
     _springFrequency = 0.8; 
     _resistanceFactor = 500; 
    } 
    return self; 
} 

-(void)prepareLayout { 
    [super prepareLayout]; 

    if (!_animator) { 
     _animator = [[UIDynamicAnimator alloc] initWithCollectionViewLayout:self]; 
     CGSize contentSize = [self collectionViewContentSize]; 
     NSArray *items = [super layoutAttributesForElementsInRect:CGRectMake(0, 0, contentSize.width, contentSize.height)]; 

     for (UICollectionViewLayoutAttributes *item in items) { 
      UIAttachmentBehavior *spring = [[UIAttachmentBehavior alloc] initWithItem:item attachedToAnchor:item.center]; 

      spring.length = 0; 
      spring.damping = self.springDamping; 
      spring.frequency = self.springFrequency; 

      [_animator addBehavior:spring]; 
     } 
    } 
} 

-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect { 
    return [_animator itemsInRect:rect]; 
} 

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath { 
    return [_animator layoutAttributesForCellAtIndexPath:indexPath]; 
} 

-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds { 
    UIScrollView *scrollView = self.collectionView; 
    CGFloat scrollDelta = newBounds.origin.y - scrollView.bounds.origin.y; 
    CGPoint touchLocation = [scrollView.panGestureRecognizer locationInView:scrollView]; 

    for (UIAttachmentBehavior *spring in _animator.behaviors) { 
     CGPoint anchorPoint = spring.anchorPoint; 
     CGFloat distanceFromTouch = fabs(touchLocation.y - anchorPoint.y); 
     CGFloat scrollResistance = distanceFromTouch/self.resistanceFactor; 

     id<UIDynamicItem> item = [spring.items firstObject]; 
     CGPoint center = item.center; 

     if (scrollDelta > 0) { 
      center.y += MIN(scrollDelta, scrollDelta * scrollResistance); 
     } 

     item.center = center; 
     [_animator updateItemUsingCurrentState:item]; 
    } 
    return NO; 
} 

@end 

在这里引起这种循环运动会发生什么?我只是改变了我的UIAttachmentAttributes中心的Y轴属性。

center.y += MIN(scrollDelta, scrollDelta * scrollResistance); 

我在这里错过了什么? (在其他项目中尝试了这种确切的布局,似乎工作)。

编辑:

我上传了一个样本项目(删除),自定义集合视图布局类叫做VVSpringCollectionViewFlowLayout.m,没有太多的时间去考虑这个太多我自己,因为我有很多最近在做工作。

当示例项目运行(Xcode 7 beta或更高版本)时,系统会提示您使用滑块,一直拖动到右侧以可视化“集合视图单元”。

下面的代码应该可以帮助你指出正确的方向。它还有一些额外功能 - 比如清理不必要的动画师行为(如果不在视图中),跟踪触摸动画师的行为。剥离旧项目,所以应该工作。有示范创建视频Github的示例项目包括 - https://github.com/serendipityapps/SpringyCollectionView

@interface VVSpringCollectionViewFlowLayout() 

@property (nonatomic, strong) UIDynamicAnimator *dynamicAnimator; 
@property (nonatomic, strong) NSMutableSet *visibleIndexPathsSet; 
@property (nonatomic, assign) CGFloat latestDelta; 

@end 

@implementation VVSpringCollectionViewFlowLayout 

- (id)init { 
    if (self = [super init]) { 
     self.dynamicAnimator = [[UIDynamicAnimator alloc] initWithCollectionViewLayout:self]; 
     self.visibleIndexPathsSet = [NSMutableSet set]; 
    } 
    return self; 
} 

- (id)initWithCoder:(nonnull NSCoder *)aDecoder { 
    if (self = [super initWithCoder:aDecoder]) { 
     self.dynamicAnimator = [[UIDynamicAnimator alloc] initWithCollectionViewLayout:self]; 
     self.visibleIndexPathsSet = [NSMutableSet set]; 
    } 
    return self; 
} 

-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect { 
    return [self.dynamicAnimator itemsInRect:rect]; 
} 

-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath { 
    return [self.dynamicAnimator layoutAttributesForCellAtIndexPath:indexPath]; 
} 

- (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { 
    return [self.dynamicAnimator layoutAttributesForSupplementaryViewOfKind:kind atIndexPath:indexPath]; 
} 


-(void)prepareLayout { 
    [super prepareLayout]; 

    // Need to enlarge visible rect slightly to avoid flickering. 
    CGRect visibleRect = CGRectInset((CGRect){.origin = self.collectionView.bounds.origin, .size = self.collectionView.frame.size}, -100, -100); 

    NSArray *itemsInVisibleRectArray = [super layoutAttributesForElementsInRect:visibleRect]; 

    NSArray *cells = [itemsInVisibleRectArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(UICollectionViewLayoutAttributes *item, NSDictionary *bindings) { 
     return !item.representedElementKind; 
    }]]; 

    NSSet *itemsIndexPathsInVisibleRectSet = [NSSet setWithArray:[cells valueForKey:@"indexPath"]]; 

    // Remove any behaviours that are no longer visible. 
    NSArray *noLongerVisibleBehavioursCells = [self.dynamicAnimator.behaviors filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(UIAttachmentBehavior *behaviour, NSDictionary *bindings) { 

     UICollectionViewLayoutAttributes *item= (UICollectionViewLayoutAttributes*)[[behaviour items] firstObject]; 
     if (!item.representedElementKind) { 
      BOOL currentlyVisible = [itemsIndexPathsInVisibleRectSet member:[item indexPath]] != nil; 
      return !currentlyVisible; 
     } 
     else { 
      return NO; 
     } 
    }]]; 

    [noLongerVisibleBehavioursCells enumerateObjectsUsingBlock:^(UIAttachmentBehavior *behaviour, NSUInteger index, BOOL *stop) { 
     UICollectionViewLayoutAttributes *item = (UICollectionViewLayoutAttributes*)[[behaviour items] firstObject]; 
     [self.dynamicAnimator removeBehavior:behaviour]; 
     [self.visibleIndexPathsSet removeObject:[item indexPath]]; 
    }]; 


    // Add any newly visible behaviours. 
    CGPoint touchLocation = [self.collectionView.panGestureRecognizer locationInView:self.collectionView]; 

    // A "newly visible" item is one that is in the itemsInVisibleRect(Set|Array) but not in the visibleIndexPathsSet 
    NSArray *newlyVisibleItems = [cells filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(UICollectionViewLayoutAttributes *item, NSDictionary *bindings) { 
     BOOL currentlyVisible = [self.visibleIndexPathsSet member:item.indexPath] != nil; 
     return !currentlyVisible; 
    }]]; 

    [newlyVisibleItems enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes *item, NSUInteger idx, BOOL *stop) { 
     CGPoint center = item.center; 
     UIAttachmentBehavior *springBehaviour = [[UIAttachmentBehavior alloc] initWithItem:item attachedToAnchor:center]; 

     springBehaviour.length = 0.0f; 
     springBehaviour.damping = 0.8f; 
     springBehaviour.frequency = 1.0f; 

     // If our touchLocation is not (0,0), we'll need to adjust our item's center "in flight" 
     if (!CGPointEqualToPoint(CGPointZero, touchLocation)) { 
      CGFloat yDistanceFromTouch = fabs(touchLocation.y - springBehaviour.anchorPoint.y); 
      CGFloat xDistanceFromTouch = fabs(touchLocation.x - springBehaviour.anchorPoint.x); 
      CGFloat scrollResistance = (yDistanceFromTouch + xDistanceFromTouch)/1500.0f; 

      if (self.latestDelta < 0) { 
       center.y += MAX(self.latestDelta, self.latestDelta*scrollResistance); 
      } 
      else { 
       center.y += MIN(self.latestDelta, self.latestDelta*scrollResistance); 
      } 
      item.center = center; 
     } 

     [self.dynamicAnimator addBehavior:springBehaviour]; 
     [self.visibleIndexPathsSet addObject:item.indexPath]; 
    }]; 
} 


-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds { 

    UIScrollView *scrollView = self.collectionView; 
    CGFloat delta = newBounds.origin.y - scrollView.bounds.origin.y; 

    self.latestDelta = delta; 

    CGPoint touchLocation = [self.collectionView.panGestureRecognizer locationInView:self.collectionView]; 

    __block UIDynamicAnimator *weakDynamicAnimator = self.dynamicAnimator; 

    [self.dynamicAnimator.behaviors enumerateObjectsUsingBlock:^(UIAttachmentBehavior *springBehaviour, NSUInteger idx, BOOL *stop) { 

     CGFloat yDistanceFromTouch = fabs(touchLocation.y - springBehaviour.anchorPoint.y); 
     CGFloat xDistanceFromTouch = fabs(touchLocation.x - springBehaviour.anchorPoint.x); 
     CGFloat scrollResistance = (yDistanceFromTouch + xDistanceFromTouch)/1500.0f; 

     UICollectionViewLayoutAttributes *item = (UICollectionViewLayoutAttributes*)[springBehaviour.items firstObject]; 
     CGPoint center = item.center; 
     if (delta < 0) { 
      center.y += MAX(delta, delta*scrollResistance); 
     } 
     else { 
      center.y += MIN(delta, delta*scrollResistance); 
     } 
     item.center = center; 

     [weakDynamicAnimator updateItemUsingCurrentState:item]; 
    }]; 

    return NO; 
} 

@end 

答案SampleCode: 因为被编程生成项目的大小,而不是圆形的样本代码显示这个奇怪的摆动效果 - 从精密该计算为UIDynamics和Physics引擎带来了问题,并且它永远达不到平衡。简单地四舍五入生成的项目大小为物理学提供了一个机会。请参阅NoteCollectionViewController.swift行77.

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 
    let w = round(CellAspectRatio.width * collectionView.frame.width) 
    let h = round(CellAspectRatio.height * collectionView.frame.height) 
    return CGSizeMake(w, h) 
} 
+0

嗨,这里是一个最小项目的链接,显示了类的工作原理,https://www.dropbox.com/s/m6wsfqbaim3xhmq/SpringyCollectionView.zip?dl=0 –

+0

该项目并没有实际编译,但无论如何......出于某种原因,我在我的项目中看到了上述行为。这不回答原来的问题... 我可能会继续并发布一个小样本项目揭露这个问题。 – Goles

+0

嘿,不知道为什么不在你的系统上编译。这是一个从头开始创建项目的5分钟视频。 https://www.dropbox.com/s/2ffptx2wfdbmm5g/OriginalSpringyDemo.mp4?dl=0也许你会发现一些东西。我在我的项目中尝试了多种变化,例如水平跳动等,但无法再现您的问题。一个示例项目将非常适合亲眼看到问题。 –

那么接受的答案大多是正确的。它实际上可能会在屏幕比例为3的iPhone +上再次出现相同的症状。以1/3或2/3点的一些不合理的数字拉中心,将再次导致永久性的圆周运动。

舍入为偶数 2.0 * floorf((number/2.0) + 0.5) - 从其他帖子修改。 这将确保中心是整数,而不是非理性。 然后通过只在一个维度拉动中心会使bug消失。