iOS UITableView的cellForRowAtIndexPath方法不執行的原因

來源:互聯網
上載者:User

眾所周知,UITableView是非常常用的UI,但是有時候我們會碰到UITableViewUITableViewDataSource協議中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;
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.