UITableView всегда в простом режиме, хотя определено иначе в XIB - PullRequest
0 голосов
/ 28 сентября 2011

Я создал UITableView, используя предустановки, используя опцию UITableViewController в диалоговом окне New File.Я установил стиль для группировки с помощью Interface Builder.

Однако таблица всегда отображается в plain style.

Источник данных состоит из двух разделов с двумя элементами в каждом и заголовком раздела.,Все хорошо, но стиль неправильный.Через NSLog я подтвердил, что стиль действительно установлен как обычный во время выполнения.Я что-то упустил?

РЕДАКТИРОВАТЬ: Вот мой код.Как я уже говорил, вызовы NSLog возвращают ожидаемые значения.

@implementation EventTableView

@synthesize tableView = _tableView;

- (id)initWithStyle:(UITableViewStyle)style
{
   self = [super initWithStyle:style];
   return self;
}

- (void)didReceiveMemoryWarning
{
   [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
   [super viewDidLoad];

   [[self navigationItem] setTitle:@"Events"];
   self.clearsSelectionOnViewWillAppear = YES;

   NSLog(@"Table view style: %@.", (self.tableView.style == UITableViewStylePlain ? @"Plain" : @"Grouped"));
}

- (void)viewDidUnload
{
   [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
   [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
   [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
   [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
   [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
   // Return YES for supported orientations
   return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_appDelegate == nil) {
       _appDelegate = (MyAppDelegate *) [[UIApplication sharedApplication] delegate];
    }
    return _appDelegate.model.eventSections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    Section* eventSection = [_appDelegate.model.eventSections objectAtIndex:section];
    NSInteger result = [eventSection getCountAsInteger];
    if (eventSection != nil && result >= 0) {
       NSLog(@"Got %d rows in event section %d.", result, section);
       return result;
    } else {
       NSLog(@"Can't get event section row count. Defaulting to 0.");
       return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"EventCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
       cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault   reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    cell.textLabel.text = @"Test";
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    Section* eventSection = [_appDelegate.model.eventSections objectAtIndex:section];
    return eventSection.name;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Pressed row...");
}

@end

РЕДАКТИРОВАТЬ: Чтобы помочь, я включил скриншот Interface Builder (стиль установлен на group).Interface Builder

Ответы [ 3 ]

1 голос
/ 28 сентября 2011

Если у вас нет где-нибудь кода, который вызывает метод - (id)initWithStyle:(UITableViewStyle)style вашего представления с неверным стилем (что я ожидаю), Вы можете переписать свой метод инициализации в

- (id)initWithStyle:(UITableViewStyle)style
{
   self = [super initWithStyle:UITableViewStyleGrouped];
   return self;
}

Во-первых, вы можете попытаться убедиться, что вы сохранили .xib в Xcode, очистить и перестроить свое приложение, чтобы вы были уверены, что ваши изменения действительно выполняются на устройстве / симуляторе.

1 голос
/ 28 сентября 2011

Обновлено:

Найдите

- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style

в вашем контроллере, установите style = UITableViewStyleGrouped; перед вызовом super

0 голосов
/ 29 сентября 2011

Это действительно безумие.Я нашел какую-то работу вокруг.

Я добавил стандарт UIViewController и реализовал на нем протоколы UITableViewDelegate и UITableViewDataSource.

В XIB / NIB я удалилстандарт UIView и добавлено UITableView.Я подключил выходы представления datasource и delegate к объекту «Владелец файла», а выход представления представления «Владелец файла» - к UITableView.

Теперь я могу установить стиль таблицы для группировки.Пока все отлично работает.Тем не менее, я не понимаю, что действительно отличается от использования UITableViewController ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...