我第一次尝试在不使用 Storyboard的情况下创建一个极其简单的应用程序。
我只是想在应用程序加载后将 tableView 显示为我的第一个屏幕。我创建了一个 UIView 类,然后在 viewDidLoad 方法中创建了一个 TableView 。
在我的委托(delegate)类中,我创建了我的类的一个实例,然后将其设置为我的 Root View Controller 。
当我运行应用程序时,tableView 显示,但单元格上不显示数字。我一直在阅读有关此的苹果文档,但到目前为止还没有找到解决方案。它可能很小,但我似乎无法弄清楚。
如您所见,我创建了一个数组,其中填充了非常简单的字符串,这些字符串只是数字。我希望每个数字都显示在表格 View 中的一个单元格上,但是当表格 View 加载时,单元格是空白的。
#import "NumbersViewController.h"
@interface NumbersViewController ()
@end
@implementation NumbersViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UITableView *tableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain];
tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
tableView.delegate = self;
tableView.dataSource = self;
[tableView reloadData];
self.view = tableView;
self.numArray = [NSMutableArray array];
[self.numArray addObject:@"1"];
[self.numArray addObject:@"2"];
[self.numArray addObject:@"3"];
[self.numArray addObject:@"4"];
[self.numArray addObject:@"5"];
[self.numArray addObject:@"6"];
[self.numArray addObject:@"7"];
[self.numArray addObject:@"8"];
[self.numArray addObject:@"9"];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Number of rows is the number of time zones in the region for the specified section.
return [self.numArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"MyReuseIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}
NSString *number = [self.numArray objectAtIndex:indexPath.row];
cell.textLabel.text = number;
return cell;
}
@end
最佳答案
在 reloadData
之后添加数据
//Delegate methods called
[tableView reloadData];
self.view = tableView;
// data added
self.numArray = [NSMutableArray array];
[self.numArray addObject:@"1"];
解决方案
将 numArray
初始化和播种代码移至 reloadData
关于ios - 数据未加载到以编程方式创建的 tableView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24917769/