Я хочу задать вопрос о UITableView объекта C. Я пишу программу, и я бы хотел создать программный интерфейс программно. Однако я не знаю, как программно отображать таблицу. У меня уже есть NSMutableArray для хранения отображаемых данных. И я создаю объект UITableView *tableData;
, что я должен сделать для следующего шага? Большое вам спасибо.
Как отображать UITableView программно?
Ответ 1
после написания выше кода вам нужно реализовать метод делегата UITableView.
это метод делегирования нагрузки UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [your array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
cell.textLabel.text = [yourarray objectAtIndex:indexPath.row];
return cell;
}
Ответ 2
Что-то вроде этого должно сделать трюк (предполагая, что это выполняется изнутри вашего контроллера вида, и у вас есть свойство, настроенное для представления таблицы):
tableView = [[[UITableView alloc] initWithFrame:CGRectMake(...) style:UITableViewStylePlain] autorelease];
tableView.dataSource = self;
tableView.delegate = self;
[self.view addSubview:tableView];
Если вы замените CGRectMake(...)
на любую позицию/размер, который вы хотите.
Ответ 3
- Создайте новый класс, который наследуется от UIViewController.
- Сопоставьте протокол UITableViewDataSource.
- Объявите представление таблицы.
Ваш заголовочный файл должен выглядеть следующим образом:
@interface MyViewController : UIViewController <UITableViewDataSource> {
}
@property (nonatomic, retain) UITableView *tableView;
@end
В методе viewLoad вашего класса:
- Создать представление таблицы с помощью initWithFrame. Используйте размеры 320x460 для полной высоты. Удалите 44 с высоты, если у вас есть панель навигации и 49, если у вас есть панель вкладок.
- Создайте новое представление.
- Добавить представление таблицы в новое представление.
- Установите представление контроллера в новое представление.
- Установите источник данных представления таблицы в свой экземпляр (self).
- Реализовать два необходимых метода источника данных: tableView: cellForRowAtIndexPath и tableView: numberOfRowsInSection
Ваш файл реализации должен выглядеть следующим образом:
#import "MyViewController.h"
@implementation MyViewController
@synthesize tableView=_tableView;
- (void)dealloc
{
[_tableView release];
[super dealloc];
}
#pragma mark - View lifecycle
- (void)loadView
{
UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 460.0) style:UITableViewStylePlain];
self.tableView = tableView;
[tableView release];
UIView *view = [[UIView alloc] init];
[view addSubview:self.tableView];
self.view = view;
[view release];
self.tableView.dataSource = self;
}
- (void)viewDidUnload {
self.tableView = nil;
[super viewDidUnload];
}
#pragma mark - Table view data source
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyCellIdentifier = @"MyCellIdentifier";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:MyCellIdentifier];
if(cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyCellIdentifier] autorelease];
}
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 5;
}
@end
Ответ 4
Может быть, он также поможет вам всем, кто там новый.
- (void)viewDidLoad
{
[super viewDidLoad];
// init table view
tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
//or, you may do that
//tableView = [[UITableView alloc] init];
//tableView.frame = CGRectMake:(5 , 5 , 320 , 300);
// must set delegate & dataSource, otherwise the the table will be empty and not responsive
tableView.delegate = self;
tableView.dataSource = self;
tableView.backgroundColor = [UIColor cyanColor];
// add to canvas
[self.view addSubview:tableView];
}
#pragma mark - UITableViewDataSource
// number of section(s), now I assume there is only 1 section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
{
return 1;
}
// number of row in the section, I assume there is only 1 row
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
// the cell will be returned to the tableView
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"HistoryCell";
// Similar to UITableViewCell, but
JSCustomCell *cell = (JSCustomCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[JSCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
// Just want to test, so I hardcode the data
cell.descriptionLabel.text = @"Testing";
return cell;
}
@end