当用户在UITableView中向下滚动时,我们如何跟踪每个UITableViewCell视图?用户需要查看单元格一段时间(1秒)才能将其计为视图。
下面的基本跟踪无法给出准确的结果,因为用户可以快速滚动,不会被视为单元格视图。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
[self logCellView:indexPath objectId:object.objectId];
}
或
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
[self logCellView:indexPath objectId:object.objectId];
}
然后
-(void)logCellView:(NSIndexPath *)indexPath objectId:(NSString *)objectId {
// Log the cell view with any analytics tool here
}
答案 0 :(得分:4)
首先是自定义单元格:
#import <UIKit/UIKit.h>
@interface MyCell : UITableViewCell
@property (assign, nonatomic) NSTimeInterval time;
@end
主要代码:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath];
return cell;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
MyCell *myCell = (MyCell *)cell;
myCell.time = [[NSDate date] timeIntervalSince1970];
}
-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
MyCell *myCell = (MyCell *)cell;
NSTimeInterval startTime = myCell.time;
NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
if (currentTime - startTime >= 1) {
NSLog(@"Logging.. %i.Row Display Time = %f", indexPath.row, currentTime-startTime);
}
}
答案 1 :(得分:0)
一种解决方案可能在下面,但有一个更稳定的&amp;安全的方式?
-(void)logCellView:(NSIndexPath *)indexPath object:(NSString *)object {
// Set the timer to log the view since we don't want to log fast scrolls
if (indexPath.row >= [logViewTimers count] && object) {
[logViewTimers insertObject:[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(logCellViewQuery:) userInfo:object repeats:NO] atIndex:indexPath.row];
} else {
// Cell is viewed again, set a longer interval
[logViewTimers replaceObjectAtIndex:indexPath.row withObject:[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(logCellViewQuery:) userInfo:object repeats:NO]];
}
}
-(void)logCellViewQuery:(NSTimer*)theTimer {
NSLog (@"Will save the log for: %@", (NSString*)[theTimer userInfo]);
// Query here (hidden for security)
}
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"Gone indexPath: %ld",(long)indexPath.row);
// Kill the timer to log the view since user scrolled fast
if (indexPath.row < [logViewTimers count]) {
if (((NSTimer*)[logViewTimers objectAtIndex:indexPath.row])) {
[((NSTimer*)[logViewTimers objectAtIndex:indexPath.row]) invalidate];
}
}
}