Создание программы TableVIew с помощью Objective-C iOS
Я новичок в разработке приложений для iOS и самой Objective C, поэтому у меня есть очень простой вопрос.
В настоящее время у меня есть следующий метод, который вызывается из нажатия кнопки ToolBar. Этот метод предназначен для создания представления таблицы в переменной frame fr.
- (IBAction)addGolfer:(id)sender {
CGRect fr = CGRectMake(101, 45, 100, 416);
UITableView *tabrleView = [[UITableView alloc]
initWithFrame:fr
style:UITableViewStylePlain];
tabrleView.autoresizingMask =
UIViewAutoresizingFlexibleHeight |
UIViewAutoresizingFlexibleWidth;
tabrleView.delegate = self;
tabrleView.dataSource = self;
[tabrleView reloadData];
self.view = tableView;
}
Результат вызова этого метода не является тем, что я ожидаю. Вместо создания представления таблицы в фрейме "fr" вид таблицы заполняет весь экран.
Снова я совершенно новый и ценю любые ответы и любые предложения. Спасибо!
Ответы
Ответ 1
Когда вы устанавливаете свойства dataSource
и delegate
для своего UITableView
, это означает, что вы должны записать хотя бы эти методы для dataSource
:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
Если вы этого не сделаете, это будет краш. Вы получите это ( этот код может содержать синтаксические или логические ошибки - я написал его в блокноте):
@interface YourViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
UITableView *firstTableView;
UITableView *secondTableView;
}
@end
//
@implementation YourViewController
#pragma mark - Objects Processing
- (void)addGolfer:(UIBarButtonItem *)sender {
if (secondTableView) {
[secondTableView removeFromSuperView];
secondTableView = nil;
}
secondTableView = [[UITableView alloc] initWithFrame:CGRectMake(101, 45, 100, 416)];
secondTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
secondTableView.delegate = self;
tabrleView.dataSource = self;
[self.view addSubview:secondTableView];
}
#pragma mark - TableView DataSource Implementation
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == firstTableView) { // your tableView you had before
return 20; // or other number, that you want
}
else if (tableView == secondTableView) {
return 15; // or other number, that you want
}
}
- (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];
cell.backgroundView = [[UIView alloc] init];
[cell.backgroundView setBackgroundColor:[UIColor clearColor]];
[[[cell contentView] subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
if (tableView == firstTableView) { // your tableView you had before
// ...
}
else if (tableView == secondTableView) {
cell.titleLabel.text = [NSString stringWithFormat:@"Cell %d", indexPath.row + 1];
}
return cell;
}
@end
Ответ 2
Шаг 1: Добавить делегат UITableViewDataSource,UITableViewDelegate
@interface viewController: UIViewController<UITableViewDataSource,UITableViewDelegate>
{
UITableView *tableView;
}
Шаг 2:
-(void)viewDidLoad
{
tableView=[[UITableView alloc]init];
tableView.frame = CGRectMake(10,30,320,400);
tableView.dataSource=self;
tableView.delegate=self;
tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
[tableView reloadData];
[self.view addSubview:tableView];
}
Шаг 3: Свойства для таблицы (строки и столбцы)
//- Без строк в таблице
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 10;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
//- высота заголовка таблицы при необходимости
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 50;
}
//- Назначение данных ячейкам
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath] ;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[your_array objectAtIndex:indexPath.row]; ***(or)*** cell.textLabel.text = @"Hello";
return cell;
}
//- Операция, когда сенсорные элементы
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Your custom operation
}
Ответ 3
Вместо того, чтобы устанавливать представление UIViewController
, добавьте tableView в качестве подвью.
Вместо:
self.view = tableView;
Сделайте это:
[self.view addSubview:tableView];
Это будет правильно соответствовать установленному кадру.