【问题标题】:iOS - TableView willDisplayCell animation only happen when user scrolling down not to the topiOS - TableView willDisplayCell 动画仅在用户向下滚动而不是顶部时发生
【发布时间】:2016-10-31 05:26:09
【问题描述】:
您好,当用户向下滚动时,如果用户滚动到顶部,则会为表格视图单元格设置动画,通常会在没有动画的情况下移动。
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cells forRowAtIndexPath:(NSIndexPath *)indexPath{
cells.alpha = 0.0;
[UIView animateWithDuration:0.4 animations:^{
cells.alpha = 1.0;
}];
}
我试过这样,但动画总是发生
【问题讨论】:
标签:
ios
objective-c
uitableview
animation
tableview
【解决方案1】:
使用 Bool 属性“isAnimated”创建自定义单元格。默认情况下,“isAnimated”值为“NO”。
并在willDisplayCell:(UITableViewCell *)cell 方法中更改代码。
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
//Typecast UITableViewCell to CustomCell. ex: CustomCell *objCell = (CustomCell *)cell
// check isAnimated or not
if(cell.isAnimated) return;
cell.alpha = 0.0;
[UIView animateWithDuration:0.4 animations:^{
cell.alpha = 1.0;
cell.isAnimated = YES;
}];
}
这里的单元格引用是自定义单元格引用。我希望这段代码对你有用
【解决方案2】:
UITableView 是 UIScrollView 的子类,UITableViewDelegate 符合 UIScrollViewDelegate。所以你附加到table view的delegate会得到scrollViewDidScroll:等事件,你可以在table view上调用contentOffset等方法来查找滚动位置。
访问苹果文档以获取有关UIScrollViewDelegate的更多信息
使用 scrollViewDidScroll 方法,然后在那里放置一个条件来查找滚动方向。并在向下滚动时制作动画。
可以使用如下代码:
(void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGPoint offset = aScrollView.contentOffset;
CGRect bounds = aScrollView.bounds;
CGSize size = aScrollView.contentSize;
UIEdgeInsets inset = aScrollView.contentInset;
float y = offset.y + bounds.size.height - inset.bottom;
float h = size.height;
// NSLog(@"offset: %f", offset.y);
// NSLog(@"content.height: %f", size.height);
// NSLog(@"bounds.height: %f", bounds.size.height);
// NSLog(@"inset.top: %f", inset.top);
// NSLog(@"inset.bottom: %f", inset.bottom);
// NSLog(@"pos: %f of %f", y, h);
float reload_distance = 10;
if(y > h + reload_distance) {
//write your code here to animate
//cells.alpha = 0.0;
//[UIView animateWithDuration:0.4 animations:^{
//cells.alpha = 1.0;
//}];
}
}