您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

iOS 排查:UITableView 的 cellForRowAtIndexPath 不執行的原因

編輯:iOS 7 技巧

下面來看一篇關於 iOS 中 UITableView 的 cellForRowAtIndexPath 方法遲遲不執行的原因與解決辦法,具體步驟如下。

眾所周知,UITableView 是極為常用的 UI 組件,但有時我們會遇到 UITableViewDataSource 協議裡 cellForRowAtIndexPath 遲遲不被調用的情況,原因可能有以下幾種:

1.tableView 的寬度或高度等於 0;
此時 numberOfSectionsInTableView 和 numberOfRowsInSection 都會執行,而 cellForRowAtIndexPath 不執行。

2.沒有設置 tableView 的 dataSource 屬性;
出現這種情況可能是因為:
(1)自己疏忽忘了寫;
(2)mainTableView.delegate = self; 寫了兩次,就像這樣:
mainTableView.delegate = self;
mainTableView.delegate = self;
這就純屬筆誤了。
此時 UITableViewDataSource 協議中的任何方法都不會執行。

3.numberOfSectionsInTableView 方法返回值為 0;
此時 numberOfSectionsInTableView 會執行,而 numberOfRowsInSection 不會被執行。

4.numberOfRowsInSection 方法返回 0;
此時 cellForRowAtIndexPath 不會被執行。

部分測試代碼:

#import "ViewController.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
{
UITableView *mainTableView;
}
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

[self initUI];
}

- (void)initUI
{
//高度設置為132是因為不實現UITableViewDelegate中的heightForRowAtIndexPath方法,cell默認高度為44,132 = 44 * 3;
mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, 375, 132) style:UITableViewStylePlain];
mainTableView.delegate = self;
mainTableView.dataSource = self;
[self.view addSubview:mainTableView];
}

#pragma mark -- <UITableViewDelegate,UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSLog(@"numberOfSectionsInTableView");
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(@"numberOfRowsInSection");
return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"cellForRowAtIndexPath");
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cellID"];

cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];

return cell;
}

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved