2009-07-15 10 views
4

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

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

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

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

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

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

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

ответ

7

Конечно метод reloadData на UITableView будет делать трюк

+0

Going добавить пояснение к моей должности, почему я не думаю, что я могу использовать reloadData. – JonB

+0

При дальнейшей проверке и поиске учебника, касающегося того, что я хочу сделать, я буду выглядеть очень глупо, если попытаюсь оправдать использование reloadData. Извините за расточительный вопрос. – JonB

3

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

Я заполнил очень простой пример, который извлекает данные таблицы из массива и отображается из делегата приложения. Поскольку вы предложили отправить сообщение 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

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

Этот пример подходит для ситуации, когда мы загружаем некоторые данные с сервера (например, 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]; 
} 
Смежные вопросы