Представить представление по умолчанию вместо просмотра таблицы, если источник данных пуст - PullRequest
4 голосов
/ 07 сентября 2010

Приложение для iOS, над которым я сейчас работаю, основано на вкладках, и одна из вкладок - UITableViewController.

Дело в том, что когда я открываю эту вкладку с пустым источником данных (по какой-либо причине)Я хотел бы привести другое представление, с каким-нибудь сообщением / изображением, вместо пустого представления, которое я получаю с помощью tableviewcontroller.

Я пробовал что-то подобное:

- (void)viewWillAppear:(BOOL)animated {
    if ([myData count] == 0) {
        if (!emptyView) {
            emptyView = [[UIView alloc] initWithFrame:self.view.frame];
            UILabel *emptyMsg = [[UILabel alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 2, self.view.frame.size.width, 20)];
            emptyMsg.text = @"This is Empty !";
            emptyMsg.textAlignment = UITextAlignmentCenter;

            [emptyView addSubview:emptyMsg];
        }

        [self.view insertSubview:emptyView atIndex:0];
    }

    else {
        if (emptyView != nil) { [emptyView removeFromSuperview]; emptyView = nil; }
        [self.tableView reloadData];
        [super viewWillAppear:animated];
    }
}

С emptyView , определенным как iVar в контроллере представления.

Но это не работает, как ожидалось, и я не могу найти причину: /

Может любойиз вас на это взглянуть и дать мне правильный способ сделать такое поведение?

Спасибо,

Ответы [ 3 ]

4 голосов
/ 17 апреля 2012

Я решил эту проблему, добавив UIView в заголовок таблицы с размером кадра, равным размеру таблицы, и запретил взаимодействие с пользователем при просмотре таблицы:

    UIView *emptyView = [[UIView alloc] initWithFrame:self.tableView.frame];
    /* Customize your view here or load it from a NIB */
    self.tableView.tableHeaderView = emptyView;
    self.tableView.userInteractionEnabled = NO;

Когда у вас есть данные, вы просто удаляете заголовок и включаете взаимодействие с пользователем:

    self.tableView.tableHeaderView = nil;
    self.tableView.userInteractionEnabled = YES;
1 голос
/ 07 сентября 2010

UITableViewController не позволяет добавлять подпредставления в его представление (tableView).

Вы должны сделать UIViewController и добавить UITableView самостоятельно с опциональным emptyView.

Не забудьте установить dataSource и delegate!

Обновление: я создал подкласс UIViewController, чтобы избежать имитации UITableViewController каждый раз.

//
//  GCTableViewController.h
//  GCLibrary
//
//  Created by Guillaume Campagna on 10-06-17.
//  Copyright 2010 LittleKiwi. All rights reserved.
//

#import <UIKit/UIKit.h>

//Subclass of UIViewController that mimicks the UITableViewController except that the tableView is a subview of self.view and allow change of the frame of the tableView

@interface GCTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, readonly) UITableView *tableView;

- (id) initWithStyle:(UITableViewStyle)style;

//Subclass if you want to change the type of tableView. The tableView will be automatically placed later
- (UITableView*) tableViewWithStyle:(UITableViewStyle) style;

@end

.m

//
//  GCTableViewController.m
//  GCLibrary
//
//  Created by Guillaume Campagna on 10-06-17.
//  Copyright 2010 LittleKiwi. All rights reserved.
//

#import "GCTableViewController.h"

@implementation GCTableViewController

@synthesize tableView;

- (id) initWithStyle:(UITableViewStyle) style {
    if (self = [super initWithNibName:nil bundle:nil]) {
        tableView = [[self tableViewWithStyle:style] retain];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:self.tableView];

    self.tableView.frame = self.view.bounds;
    self.tableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
}

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

    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

#pragma mark TableView methods

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    return 0;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return nil;
}

#pragma mark Getter

- (UITableView *) tableViewWithStyle:(UITableViewStyle)style {
    return [[[UITableView alloc] initWithFrame:CGRectZero style:style] autorelease];
}

- (void)dealloc {
    [tableView release];
    tableView = nil;

    [super dealloc];
}


@end
0 голосов
/ 07 сентября 2010

Возможно, вы можете попытаться установить количество строк в ноль.Затем вставьте представление без результатов в качестве представления заголовка.

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