表视图无法正常工作。
问题描述:
我正在尝试创建一个实用的table view(没有xib和storyboards),但食物数组并没有在表格视图中显示出来。我将在视图控制器中发布我的所有代码。表视图无法正常工作。
Viewcontroller.h
@interface searchViewController : ViewController<UITextFieldDelegate,UISearchBarDelegate,UITableViewDataSource>{
NSMutableArray * getterms;
}
@property (strong, nonatomic) NSMutableArray* allTableData;
@property (strong, nonatomic) NSMutableArray* filteredTableData;
@property (nonatomic, assign) bool isFiltered;
@property (nonatomic, retain) UITableView *tableView;
Viewcontroller.m
-(void)viewDidLoad{
UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(10.0, 10.0, 1000.0, 200.0) style:UITableViewStylePlain];
[self.view addSubview:tableView];
self.tableView.dataSource = self;
allTableData = [[NSMutableArray alloc] initWithObjects:
[[Food alloc] initWithName:@"Steak" andDescription:@"Rare"],
[[Food alloc] initWithName:@"Steak" andDescription:@"Medium"],
[[Food alloc] initWithName:@"Salad" andDescription:@"Caesar"],
[[Food alloc] initWithName:@"Salad" andDescription:@"Bean"],
[[Food alloc] initWithName:@"Fruit" andDescription:@"Apple"],
[[Food alloc] initWithName:@"Potato" andDescription:@"Baked"],
[[Food alloc] initWithName:@"Potato" andDescription:@"Mashed"],
[[Food alloc] initWithName:@"Bread" andDescription:@"White"],
[[Food alloc] initWithName:@"Bread" andDescription:@"Brown"],
[[Food alloc] initWithName:@"Hot Dog" andDescription:@"Beef"],
[[Food alloc] initWithName:@"Hot Dog" andDescription:@"Chicken"],
[[Food alloc] initWithName:@"Hot Dog" andDescription:@"Veggie"],
[[Food alloc] initWithName:@"Pizza" andDescription:@"Pepperonni"],
nil ];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MYCellIdentifier = @"MyCellIdentifier";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:MYCellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MYCellIdentifier];
Food* food;
if(isFiltered)
food = [filteredTableData objectAtIndex:indexPath.row];
else
food = [allTableData objectAtIndex:indexPath.row];
cell.textLabel.text = food.name;
cell.detailTextLabel.text = food.description;
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int rowCount;
if(self.isFiltered)
rowCount = filteredTableData.count;
else
rowCount = allTableData.count;
return rowCount;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
答
看起来你从来没有你的表视图分配给您的控制器上添加
self.tableView = tableView
在viewDidLoad
第二线
答
确保的cellForRowAtIndexPath实际上是作为一个对象调用(使用NSlog或断点检查),如果没有,你没有设置UITableViewController的tableView到它正在控制的tableView,或者你没有设置你的dataSource Delegate。
OMG我加了它,但没有在右边线LOL。您将获得该复选标记,只需等待10分钟。 – moomoo 2013-04-08 18:59:47