UITableView中的visibleCells的用法(visibleCells帮上大忙了)

 

这两天遇到一个问题,UITableView中需要加入动画,而且每一行的速度不一样。

刚开始做时把所有的cell都遍历一遍加上动画,后来发现,如果数据很多时,就会出现各种各样的问题,而且没有显示在界面上的cell就没必要再用动画了,毕竟看不到。

后来发现UITableView中有这么一个方法:该方法是获取界面上能显示出来了cell。

- (NSArray *)visibleCells;

visible可见的。在当前页面中能看到cells都在这个数组中。

这样,我就根据这个数据来依次来遍历:

首先看一下这个Demo的效果:

http://my.csdn.net/my/album/detail/1718119


 

主要代码

 

 1 #pragma UITableView
 2 
 3 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 4 {
 5     return 1;
 6 }
 7 
 8 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
 9 {
10     return 20;
11 }
12 
13 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
14 {
15     static NSString *CellIdentifier = @"Cell";
16     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
17     if (cell == nil) {
18         cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
19         cell.selectionStyle = UITableViewCellSelectionStyleNone;
20         
21     }
22     
23     cell.textLabel.text = [NSString stringWithFormat:@"visibleCell:%d",indexPath.row];
24     
25     return cell;
26 }
27 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
28 {
29     //点击效果
30 }
31 
32 - (IBAction)btnAction:(id)sender {
33     //获取可见cells
34     visibleCells = visibleTableView.visibleCells;
35     NSLog(@"%@",visibleCells);
36     
37     UIButton *button = (UIButton*)sender;
38     CGAffineTransform transform;
39     double duration = 0.2;
40     
41     if (button.tag == 1) {
42         transform = CGAffineTransformMakeTranslation(-320, 0);
43     }else if(button.tag == 2){
44         for (UITableViewCell *cell in visibleCells) {
45             
46             [UIView animateWithDuration:duration delay:0 options:0  animations:^
47              {
48                  cell.transform = CGAffineTransformIdentity;
49 
50                  
51              } completion:^(BOOL finished)
52              {
53                  
54              }];
55              duration+=0.1;
56         }
57         return;
58     }else{
59         transform = CGAffineTransformMakeTranslation(320, 0);
60 
61     }
62     for (UITableViewCell *cell in visibleCells) {
63         
64         [UIView animateWithDuration:duration delay:0 options:0  animations:^
65          {
66              cell.transform = transform;
67              
68          } completion:^(BOOL finished)
69          {
70              
71          }];
72         duration+=0.1;
73         
74     }
75     
76 }

原文地址:https://www.cnblogs.com/A--G/p/4618464.html