如何检测 UITableView 中的最后一个可见单元格
Posted
技术标签:
【中文标题】如何检测 UITableView 中的最后一个可见单元格【英文标题】:How to detect last visible cell in UITableView 【发布时间】:2017-06-26 10:30:32 【问题描述】:我是 ios 开发新手,目前正在开发 UITableView。我想在设备屏幕上找到最后一个可见的单元格,并且屏幕底部的单元格必须是蓝色的,当单元格滚动到屏幕顶部时,它应该变成绿色。
我已经浏览了这些链接
Link1 Link2
但未能成功。谁能提供想法如何检测最后一个单元格和单元格淡出动画?
【问题讨论】:
ios uitableview fade bottom cell and top cell as you scroll的可能重复 【参考方案1】:获取最后一个可见单元格:
if let lastCell = tableView.visibleCells.last
// do something with lastCell
【讨论】:
【参考方案2】:在 Swift 3.0 中,你可以使用这个 tableview 方法。
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
let intTotalrow = tableView.numberOfRows(inSection:indexPath.section)//first get total rows in that section by current indexPath.
//get last last row of tablview
if indexPath.row == intTotalrow - 1
// call for last display
【讨论】:
【参考方案3】:@shallowThought 解决方案仅在单元格已呈现时才有效。
但是,如果您想知道最后一个单元格尚未显示和将要显示的单元格,我们可以为UITableView
创建一个扩展,如下所示:
func isLastVisibleCell(at indexPath: IndexPath) -> Bool
guard let lastIndexPath = indexPathsForVisibleRows?.last else
return false
return lastIndexPath == indexPath
这样,您可以多次检查tableView.isLastVisibleCell(...)
,直到到达实际可见的单元格。
【讨论】:
【参考方案4】:试试这个代码,它会工作
初始声明
int firstIndexRow;
int lastIndexRow;
在 ViewDidLoad() 中编写以下代码
[myTable reloadData]; //Reload because get visible last cell index row
firstIndexRow = 0;
lastIndexRow = (int)[self.myTable.indexPathsForVisibleRows lastObject].row;
NSLog(@"first : %d",firstIndexRow);
NSLog(@"Bottom : %d",lastIndexRow);
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
NSIndexPath *firstVisibleIndexPath = [[self.myTable indexPathsForVisibleRows] objectAtIndex:0];
NSIndexPath *lastObject = [self.myTable.indexPathsForVisibleRows lastObject];
firstIndexRow = (int)firstVisibleIndexPath.row;
lastIndexRow = (int)lastObject.row;
NSLog(@"first : %d",firstIndexRow);
NSLog(@"Bottom : %d",lastIndexRow);
[myTable reloadData];
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
UITableViewCell *cell = [myTable dequeueReusableCellWithIdentifier:@"cell"];
if (indexPath.row == firstIndexRow)
cell.textLabel.textColor = [UIColor blueColor];
else if (indexPath.row == lastIndexRow)
cell.textLabel.textColor = [UIColor greenColor];
else
cell.textLabel.textColor = [UIColor grayColor];
cell.textLabel.text =[namesArray objectAtIndex:indexPath.row];
return cell;
【讨论】:
以上是关于如何检测 UITableView 中的最后一个可见单元格的主要内容,如果未能解决你的问题,请参考以下文章
Swift - 当最后一行不可见时,如何对 UITableView 的最后一行执行特定操作?