【问题标题】:iOS TableView Calling numberOfRowsInSection repetitivelyiOS TableView 反复调用 numberOfRowsInSection
【发布时间】:2015-05-21 03:42:37
【问题描述】:

我以编程方式设置TableView 数据源和委托,并将必要的代码添加到视图控制器的头文件中。

在对numberOfRowsInSectionnumberOfSectionsInTableView 方法进行硬编码以返回1 并添加相应的日志后,我注意到这两种方法都被重复调用(4 次)但方法cellForRowAtIndexPath 没有被调用一次。

TableView 没有出现在屏幕上,但我认为这是因为没有显示单元格,但是在对包括cellLabel 文本在内的所有内容进行硬编码后,我不明白这两种方法是如何实现的被一遍又一遍地调用,但跳过cellForRowAtIndexPath 方法。

日志如下所示:

2015-05-20 22:39:09.595 SchoolAnalytics[28419:2137236] 节数

2015-05-20 22:39:09.595 SchoolAnalytics[28419:2137236] 行数 对于第 0 节

2015-05-20 22:39:09.595 SchoolAnalytics[28419:2137236] 节数

2015-05-20 22:39:09.595 SchoolAnalytics[28419:2137236] 行数 对于第 0 节

2015-05-20 22:39:09.598 SchoolAnalytics[28419:2137236] 节数

2015-05-20 22:39:09.598 SchoolAnalytics[28419:2137236] 行数 对于第 0 节

2015-05-20 22:39:09.598 SchoolAnalytics[28419:2137236] 节数

2015-05-20 22:39:09.598 SchoolAnalytics[28419:2137236] 行数 对于第 0 节

我如何加载单元格:

    - (void)viewDidLoad {
    [super viewDidLoad];
    targetList.delegate = self;
    targetList.dataSource = self;

// Do any additional setup after loading the view.
     }

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {
     NSLog(@"# of sections");
     return 1;    //count of section
 }


 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
     NSLog(@"Number of rows for section %li", (long)section);
     return 1;
 }



 - (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
    NSLog(@"CELL FOR ROW");
    static NSString *MyIdentifier = @"MyIdentifier";

    UITableViewCell *cell = [tableView      dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil)
     {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                  reuseIdentifier:MyIdentifier];
     }

     // Here we use the provided setImageWithURL: method to load the web image
     // Ensure you use a placeholder image otherwise cells will be initialized with no image

    cell.textLabel.text = @"Cell 1";
    return cell;
           }

我的头文件有两个委托

     @interface ClassViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>

可能很重要的一点是,这不是根视图,它是用一个segue 呈现的,并且在加载此视图时,会在顶部添加一个子视图,它是 UIView 的子类,并且必须被绘制。

【问题讨论】:

  • 让我知道您如何在 cellForRowAtIndexPath 中加载单元
  • 您可以添加一些您尝试过的代码。

标签: ios objective-c uitableview delegates


【解决方案1】:

numberOfRowsInSectionnumberOfSectionsInTableView 每当您在表格视图上调用 reloadData 时都会被调用。

【讨论】:

  • 我自己从来没有调用过 reloadData,如果我这样做了,也不应该调用 cellForRowAtIndexPath,因为我为每个部分的行数返回 1?
【解决方案2】:

每次加载数据时都会调用这些委托方法numberOfRowsInSectionnumberOfSectionsInTableView。比如如果你调用[table reloadData] 5 次,这些方法每次都会调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多