2013-03-12 16 views
0

Что я хочу: отобразить некоторый список данных в виде таблицы.Tableview с пустыми ячейками

Данные хранятся внутри одного массива путем создания разных объектов. Поэтому для каждого объекта размер массива изменяется. Поэтому моя проблема заключается в показе данных. Вместо того, чтобы полностью заполнять ячейки таблицы, некоторые ячейки остаются пустыми. Это не выглядит хорошо.

Может ли кто-нибудь объяснить, как получить представление таблицы без лишних пустых ячеек?

Вот как я организовать данные:

Recipe *recipe1 = [Recipe new]; 


recipe1.ingredients = [NSArray arrayWithObjects:@"1. Fish - 500 g .",@"2. Onion (Big) - 2 nos (Chopped)",@"3. Garlic (Chopped) - 3 flakes",@"4. Green chillies - 2 nos (Chopped)",@"5. Chilly powder - 3/4 tbsp ",@"6. Coriander powder - 1/2 tsp ",nil]; 


Recipe *recipe2 = [Recipe new]; 

recipe2.ingredients = [NSArray arrayWithObjects:@"1. fish - 300 gm",@"2. Tomato(medium) - 1 no",@"3. Garlic - 10 gm",@"4. Coconut powder - 10 gm",@"5. Curry leaves - A few",@"6. Salt - As reqd",@"7. Onions(medium) - 2 nos(chopped)",@"8. Oil - 1 - 2 tbsp",nil]; 

Я хочу, чтобы показать этот список ингредиентов внутри TableView в зависимости от того, какого блюда выбрано.

Вот мои методы источника данных

- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView { 
    // Return the number of sections. 
    return 1; 
} 


- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section { 
    // Return the number of rows in the section. 
    return [data count]; 
} 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"CellIdentifier"; 

    // Dequeue or create a cell of the appropriate type. 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
     cell.accessoryType = UITableViewCellAccessoryNone; 
    } 

    [cell.textLabel setFont:[UIFont fontWithName:@"Bold" size:20]]; 

    // Configure the cell. 
    cell.textLabel.text =[data objectAtIndex:indexPath.row]; 
    return cell; 
} 
+0

будет у поста метод TableView Datasource? –

ответ

0

Внутри cellForRowAtIndexPath метода попробуйте использовать следующие

На втором выборе рецепта:

cell.textLabel.text = [recipe1.ingredients objectAtIndex:indexPath.row]; 

На втором выборе рецепта:

cell.textLabel.text = [recipe2.ingredients objectAtIndex:indexPath.row]; 
0

Изменить следующие функции: для (MAC OS)

- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView 
    { 
     if (First Recipe) 
    return [recipe1.ingredients count]; 

     else if (Second Recipe) 
    return [recipe2.ingredients count]; 

    } 

ИЛИ для прошивки:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    { 
     if (First Recipe) 
      return [recipe1.ingredients count]; 

       else if (Second Recipe) 
      return [recipe2.ingredients count]; 
    } 

После этого убедитесь, чтобы перезагрузить вид таблицы, после того, как выбор сделан. Это поможет вам.

+0

нет такого метода с именем numberOfRowsInTableView – haritha

+0

Проверьте это и узнайте: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Protocols/NSTableDataSource_Protocol/Reference/Reference.html –

+0

Я обновил ответ .. проверка сейчас. –

0

То, что вы хотите сделать, это:

Вы будете иметь массив полный Рецепт объектов &, который будет DataSource вашей Tableview. &, когда вы нажмете на любой из рецептов (имя), он будет нажать на другой контроллер представления, указав список ингредиентов, необходимых для этого рецепта, в виде таблицы (в виде списка).

Для этого сначала создайте главный контроллер представления с рецептомArray (объекты рецепта) в качестве источника данных & перечислите рецепты в виде таблицы с названием рецепта. Когда вы выберете рецепт (в вызове didSelectRowAtIndexPath вызывается), нажмите на новый контроллер представления с выбранным объектом рецепта & заполните список ингредиентов в следующем контроллере таблицы.

0

В viewDidLoad Добавить 1 Строка

tableview.tableFooterView = [[UIView alloc] init]; 

А также Добавьте это ниже метод, поэтому вы не увидите никаких дополнительных ячеек, которые являются пустыми

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Remove seperator inset 
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) { 
     [cell setSeparatorInset:UIEdgeInsetsZero]; 
    } 

    // Prevent the cell from inheriting the Table View's margin settings 
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) { 
     [cell setPreservesSuperviewLayoutMargins:NO]; 
    } 

    // Explictly set your cell's layout margins 
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) { 
     [cell setLayoutMargins:UIEdgeInsetsZero]; 
    } 
} 
Смежные вопросы