2013-09-20 5 views
1

Я очень смущаюсь этим.tableview: cellForRowAtIndexPath никогда не назывался

Я пытаюсь создать UITableView сгруппированным программно, используя единый шаблон представления из Xcode. Рассматривая интернет для некоторых примеров, нет никакой тайны, подход к этому очень прост. Я не уверен, что моя реализация неправильная или правильная, потому что метод tableView: cellForRowAtIndexPath: никогда не вызывается, а другие вызываются и возвращают целое число> 0.

Есть код, любые предложения приветствуются. Спасибо,

#import "ViewController.h" 
#import "SimpleCell.h" 

@interface ViewController() <UITableViewDelegate, UITableViewDataSource> 

@property (nonatomic, strong) UITableView *table; 
@property (nonatomic, strong) NSArray *sections; 
@property (nonatomic, strong) NSArray *section1; 
@property (nonatomic, strong) NSArray *section2; 
@property (nonatomic, strong) NSArray *section3; 

@end 

@implementation ViewController 

static NSString * const CellIdentfier = @"Cell"; 


- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    [self.view addSubview:self.table]; 
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[table]|" 
                     options:0 
                     metrics:nil 
                     views:@{@"table": self.table}]]; 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self.table reloadData]; 
    }); 

} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (UITableView *)table 
{ 
    if(!_table) 
    { 
     _table = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped]; 
     _table.delegate = self; 
     _table.dataSource = self; 
     _table.translatesAutoresizingMaskIntoConstraints = NO; 
     _table.rowHeight = 34.0f; 
     _table.separatorStyle = UITableViewCellSeparatorStyleSingleLine; 
     _table.backgroundColor = [UIColor grayColor]; 
     _table.showsVerticalScrollIndicator = NO; 
     [_table registerClass:[SimpleCell class] forCellReuseIdentifier:CellIdentfier]; 
    } 

    return _table; 
} 

- (NSArray *)sections 
{ 
    if(!_sections) 
    { 
     _sections = @[@"Section1", @"Section2", @"Section3"]; 
    } 

    return _sections; 
} 

- (NSArray *)section1 
{ 
    if(!_section1) 
    { 
     _section1 = @[@"Player a", @"Player b", @"Player c"]; 
    } 

    return _section1; 
} 

- (NSArray *)section2 
{ 
    if(!_section2) 
    { 
     _section2 = @[@"Zone a", @"Zone b", @"Zone c"]; 
    } 

    return _section2; 
} 

- (NSArray *)section3 
{ 
    if(!_section3) 
    { 
     _section3 = @[@"Area a", @"Area b", @"Area c"]; 
    } 

    return _section3; 
} 


#pragma mark - UI Table View Delegate impl 


#pragma mark - UI Table View Datasource impl 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    DLog(); 
    SimpleCell *cell = [self.table dequeueReusableCellWithIdentifier:CellIdentfier]; 

    if(!cell) 
     cell = [[SimpleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentfier]; 

    cell.label.text = [NSString stringWithFormat:@"Section: %i Row: %i", indexPath.section, indexPath.row]; 
    return cell; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    NSInteger total = 0; 
    if(section == 0) total = self.section1.count; 
    if(section == 1) total = self.section2.count; 
    if(section == 2) total = self.section3.count; 

    DLog(@"Rows: %i", total); 

    return total; 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    DLog(); 
    return self.sections.count; 
} 



@end 
+0

'NSLog'' self.section1' в 'numberOfRowsInSection:' и посмотреть, существует ли она. – Undo

+0

Да, это существует, выход: ( «Игрок a», «Игрок b», «Игрок c» ) –

ответ

1

Удалить это:

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[table]|" 
                    options:0 
                    metrics:nil 
                    views:@{@"table": self.table}]]; 

Следует назвать то.

EDIT:

Изменить это, а также:

_table = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped]; 

Это, кажется, чтобы исправить это, но я не знаю, почему. Я предполагаю, что это имеет какое-то отношение к раме таблицы, которая должна быть больше 0.

+0

Я удалил и результат тот же. Мне нужно будет добавить ограничение в любом случае, чтобы отобразить таблицу в интерфейсе, потому что я создал рамку таблицы с CGRectZero и установил для translatesAutoresizingMaskIntoConstraints значение «НЕТ». –

+0

@ JanCássio Я обновил свой ответ, посмотрю, исправляет ли он это. – random

+0

Hum, этого недостаточно, мне нужно настроить translatesAutoresizingMaskIntoConstraints на «YES», и ячейки отображаются для интерфейса. Но у меня много ошибок с ограничениями. Проверьте это: –

Смежные вопросы