在iOS 7中使用Messages应用程序进行对话时,如果您向上或向下滚动,您会注意到气泡以及更多的文字会反弹回原位。
我正在尝试在自己的表视图中复制这个效果,但是找不到方法。
我猜它是使用UIDynamics,但我不确定如何将其与滚动和内容反弹联系起来。
任何帮助将不胜感激
在iOS 7中使用Messages应用程序进行对话时,如果您向上或向下滚动,您会注意到气泡以及更多的文字会反弹回原位。
我正在尝试在自己的表视图中复制这个效果,但是找不到方法。
我猜它是使用UIDynamics,但我不确定如何将其与滚动和内容反弹联系起来。
任何帮助将不胜感激
我对那个效果也很感兴趣,在网上进行研究时,我发现了这个教程 - http://www.objc.io/issue-5/collection-views-and-uidynamics.html,它实现了相同的想法。
您可以通过以下方式为滚动视图中的内容添加弹性效果:
Set up a UIScrollview and add to your view.
mainScroller = [UIScrollView new];
mainScroller.frame = CGRectMake(0, 0, w, h);
mainScroller.bounces = true;
mainScroller.pagingEnabled = false;
mainScroller.delegate = self;
[self.view addSubview:mainScroller];
Layout a UIView and add it within your scrollview.
contentView = [UIView new];
contentView.frame = CGRectZero;
[mainScroller addSubview:contentView];
Add subviews your your 'contentView'.
UIView * unitView = [UIView new];
unitView.frame = CGRectMake(0, yOff, w, 280);
[contentView addSubview:unitView];
Resize both contentView and scrollview to fit the content. Below w is view width and yOff the total cumulative height of the content.
contentView.frame = CGRectMake(0, 0, w, yOff);
mainScroller.contentSize = CGSizeMake(w, yOff);
In your scrollViewDidScroll method, add the following code:
float y = mainScroller.contentOffset.y;
contentView.transform = CGAffineTransformMakeTranslation(0, y);
for (UIView * sub in contentView.subviews){
int index = (int)[contentView.subviews indexOfObject:sub];
float delay = index * 0.03;
float duration = 1.0f - delay;
[UIView animateWithDuration:duration
delay:delay
usingSpringWithDamping:0.8
initialSpringVelocity:0.7
options:UIViewAnimationOptionCurveEaseInOut| UIViewAnimationOptionAllowUserInteraction
animations:^{
sub.transform = CGAffineTransformMakeTranslation(0, -y);
}
completion:^(BOOL finished){
}];
}
UIViewAnimationOptionAllowUserInteraction动画选项允许您立即与内容交互。调整延迟、持续时间、弹簧阻尼和弹簧速度变量以适应您的需求。
代码可以进一步适应触摸检测;目前,弹性反弹从scrollView的顶部开始,并通过视图向下降落,对于较短的scrollViews几乎不可感知。
编辑:触摸检测
如果要允许触摸检测,请在scrollViewDidScroll方法中替换为以下行:
int index = (int)[contentView.subviews indexOfObject:sub];
int deviation = abs(touchIndex - index);
float delay = deviation * 0.03;
float duration = 1.0f - delay;
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
//grab the location of the touch event
CGPoint location = [scrollView.panGestureRecognizer locationInView:scrollView];
int yTouch = location.y; //grab y coordinate
touchIndex = (yTouch - 100) / 100; //calculate the index of the cell, where 100 is the height of the cell
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
//grab the location of the touch event
CGPoint location = [scrollView.panGestureRecognizer locationInView:scrollView];
int yTouch = location.y; //grab y coordinate
float tally = 70.0f;
for (int n = 0; n < selectedHeights.count; n++){
float cellHeight = [selectedHeights[n] floatValue];
tally += cellHeight;
if (tally > yTouch){
touchIndex = n;
break;
}
}
}