Динамическое изменение содержимого UITableView - PullRequest
5 голосов
/ 15 июля 2009

У меня есть объект NSURL, который получает данные с моего сайта на основе переменной, введенной пользователем в строку поиска.

Я разбил эти данные на NSArray.

Как только я это сделаю, я хочу отобразить данные в UITableView.

Мой вопрос такой. Можно ли динамически загружать данные в UITableView?

т.е. Программа загружается, данных нет, поэтому UITableView пуст, затем пользователь ищет одну переменную. Получает некоторые данные и содержимое загружается в UITableView. Ищет новую переменную, старые данные очищаются из UITableView и новые данные добавляются?

В настоящее время я пытаюсь сделать это с помощью построителя интерфейса, но боюсь, что мне, возможно, придется сделать мой интерфейс прагматичным, чтобы я мог уничтожить и заново создать UITableView, но я не уверен.

Спасибо за любую помощь.

Ответы [ 3 ]

8 голосов
/ 15 июля 2009

Конечно, метод reloadData в UITableView сделает свое дело

3 голосов
/ 15 июля 2009

Не бойтесь, создание подклассов UITableView очень просто. В xCode просто выберите новый файл, выберите «Классы касания какао», «Класс Objective-c» и в раскрывающемся списке «Подкласс» UITableView. xCode добавит подкласс UITableViewController с заглушками для сборки.

Я заполнил очень простой пример, который рисует данные таблицы из массива и отображается из Application Delegate. Как вы предложили, отправка сообщения reloadData в UITableView обновит отображаемые данные.

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

Ура, Нильс

//
//  MyTableViewController.m
//  TableView
//
//  Created by Niels Castle on 7/15/09.
//  Copyright 2009 Castle Andersen ApS. All rights reserved.
//

#import "MyTableViewController.h"


@implementation MyTableViewController

// Initializer do custom initialisation here
- (id)initWithStyle:(UITableViewStyle)style {
    if (self = [super initWithStyle:style]) {

      // This is the source of my data. The simplest source possible,
      // an NSMutableArray, of name. This would be the data from your web site
       array = [[NSMutableArray alloc]
        initWithObjects:@"Niels", @"Camilla", @"William", nil];
    }
    return self;
}


// How many section do we want in our table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view
// Simply the number of elements in our array of names
- (NSInteger)tableView:(UITableView *)tableView
    numberOfRowsInSection:(NSInteger)section {
    return [array count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView
    cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   // Reuse cells 
   static NSString *id = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:id];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]
            initWithStyle: UITableViewCellStyleDefault
            reuseIdentifier:CellIdentifier] autorelease];
    }

   // Simplest possible cell - displaying a name from our name array
   [[cell textLabel] setText: [array objectAtIndex:[indexPath row]]];

    return cell;
}

- (void)dealloc {
   [super dealloc];
   [array release];
}

@end


//
//  TableViewAppDelegate.m
//  TableView
//
//  Created by Niels Castle on 7/15/09.
//  Copyright Castle Andersen ApS 2009. All rights reserved.
//

#import "TableViewAppDelegate.h"
#import "MyTableViewController.h"

@implementation TableViewAppDelegate

@synthesize window;


- (void)applicationDidFinishLaunching:(UIApplication *)application {    

   MyTableViewController *twc = [[MyTableViewController alloc]
      initWithStyle: UITableViewStylePlain];
   [window addSubview: [twc view]];

    [window makeKeyAndVisible];
}


- (void)dealloc {
    [window release];
    [super dealloc];
}


@end
0 голосов
/ 24 ноября 2013

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

Этот пример соответствует ситуации, когда мы загружаем некоторые данные с сервера (например, JSON), и результат может сильно отличаться по количеству разделов и / или строк.

пустая функция, вы можете опустить ее

-(void)addToPropertiesTable {

    //fullTableData is above mentioned two dimensional array 
    int sectionsCount = _fullTableData.count;
    int count = 0;
    NSMutableArray *insertIndexPaths = [NSMutableArray array];
    NSMutableArray *deleteIndexPaths = [NSMutableArray array];

    for(int j = 0; j < sectionsCount; j++) {
        NSMutableArray *currentAdverts = [[NSMutableArray alloc] init];
        [currentAdverts addObjectsFromArray:[_fullTableData objectAtIndex:j]];
        count = [currentAdverts count];

        int currentRowsInSection = [self.propertiesTable numberOfRowsInSection:j];

        if(currentRowsInSection > 0) {
            //if any data in current tableView, lets get rid of them first
            for (int i = [self.propertiesTable numberOfRowsInSection:j] - 1; i >=0 ; i--)
            {
                [deleteIndexPaths addObject:[NSIndexPath indexPathForRow:i inSection:j]];
            }
        }
        for (NSUInteger item = 0; item < count; item++) {            
            [insertIndexPaths addObject:[NSIndexPath indexPathForRow:item inSection:j]];
        }
    }


    [self.propertiesTable beginUpdates];

    //we delete old rows - whether we need them or not
    [self.propertiesTable deleteRowsAtIndexPaths:deleteIndexPaths
                                withRowAnimation:UITableViewRowAnimationFade];
    if([self.propertiesTable numberOfSections]) {

        //if any sections, we remove them
        NSIndexSet *nsIndexSetToDelete = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0,[self.propertiesTable numberOfSections])];
        [self.propertiesTable deleteSections:nsIndexSetToDelete withRowAnimation:UITableViewRowAnimationAutomatic];
    }


    //here we have to set new sections, whether they have changed or not
    NSIndexSet *nsIndexSetToInsert = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0,sectionsCount)];
    [self.propertiesTable insertSections:nsIndexSetToInsert withRowAnimation:UITableViewRowAnimationAutomatic];

    //finally we insert rows 
    [self.propertiesTable insertRowsAtIndexPaths:insertIndexPaths
                                withRowAnimation:UITableViewRowAnimationFade];
    [self.propertiesTable endUpdates];

    //now we see the change in UI
    [self.propertiesTable reloadData];
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...