我尝试在水平 UICollectionView 中模仿消息应用程序弹簧动画
我在 UICollectionViewFlowLayout 子类中使用了 UIAttachmentBehavior。但问题是,当我水平滚动时,单元格也会垂直和水平移动,以某种方式进行旋转运动!
我已经遵循了这个教程:
使用 uikitdynamics 实现有弹性的 uicollectionviewlayout http://www.teehanlax.com/blog/implementing-a-bouncy-uicollectionviewlayout-with-uikit-dynamics/
并在我的collectionView中使用。我还关注了 WWDC 2013 session 217-Exploring Scroll Views on iOS 7。但问题仍然存在!
有谁知道我应该如何解决这个问题?
-(id)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if (self){
_dynamicAnimator = [[UIDynamicAnimator alloc] initWithCollectionViewLayout:self];
}
return self;
}
- (void)prepareLayout{
[super prepareLayout];
CGSize contentSize = [self collectionViewContentSize];
NSArray *items = [super layoutAttributesForElementsInRect:CGRectMake(0, 0, contentSize.width, 500)];
if (items.count != _dynamicAnimator.behaviors.count) {
[_dynamicAnimator removeAllBehaviors];
for (UICollectionViewLayoutAttributes *item in items) {
UIAttachmentBehavior *springBehavior = [[UIAttachmentBehavior alloc] initWithItem:item attachedToAnchor:item.center];
springBehavior.length = 0.f;
springBehavior.damping = 0.5f;
springBehavior.frequency = 0.8f;
[_dynamicAnimator addBehavior:springBehavior];
}
}
}
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
return [_dynamicAnimator itemsInRect:rect];
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
return [_dynamicAnimator layoutAttributesForCellAtIndexPath:indexPath];
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
CGFloat scrollDelta = newBounds.origin.x - self.collectionView.bounds.origin.x;
CGPoint touchLocation = [self.collectionView.panGestureRecognizer locationInView:self.collectionView];
for (UIAttachmentBehavior *springBehavior in _dynamicAnimator.behaviors) {
CGPoint anchorPoint = springBehavior.anchorPoint;
CGFloat touchDistance = fabsf(touchLocation.x - anchorPoint.x);
CGFloat resistanceFactor = 0.002;
UICollectionViewLayoutAttributes *attributes = springBehavior.items.firstObject;
CGPoint center = attributes.center;
float resistedScroll = scrollDelta * touchDistance * resistanceFactor;
float simpleScroll = scrollDelta;
float actualScroll = MIN(abs(simpleScroll), abs(resistedScroll));
if(simpleScroll < 0){
actualScroll *= -1;
}
center.x += actualScroll;
attributes.center = center;
[_dynamicAnimator updateItemUsingCurrentState:attributes];
}
return NO;
}
我的应用程序中也遇到了同样的问题。问题是这一行:UIAttachmentBehavior *springBehavior = [[UIAttachmentBehavior alloc] initWithItem:item attachedToAnchor:item.center];
问题是该项目的中心返回带小数的浮点数。然后,iOS 将它们四舍五入为小数点后 0 的浮点数,导致锚点无法很好地居中,因此项目会反弹。
解决方案是在锚定项目之前确保其框架的高度和宽度可被二整除。然后验证 item.center 返回的 X 和 Y 值是没有小数的浮点数,并且动画可以正常工作。
注意:即使在 iOS7 中工作完美,我在 iOS8 中也看到了与此类似的问题,并且此解决方案不起作用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)