我正在尝试以实用方式创建表格视图(没有xib而没有故事板),但是食物数组根本没有显示在表格视图中。我将在视图控制器中发布所有代码。
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;
}
答案 0 :(得分:1)
看起来你永远不会将你的表视图分配给你的控制器,添加
self.tableView = tableView
作为viewDidLoad
答案 1 :(得分:0)
答案 2 :(得分:0)
确保实际调用了cellForRowAtIndexPath(使用NSlog或断点进行检查),否则,您没有将UITableViewController的tableView设置为它正在控制的tableView,或者您还没有设置dataSource Delegate。