2012-02-24 2 views
12

Я только недавно начал программирование для iPhone, и я создаю приложение, которое подключается к базе данных и получает набор имен строк и отображает их. Когда выбрано, изменение цвета фона строк, т. Е. Вы можете сделать несколько выборов, и все они будут разных цветов. Поэтому я возвращаю XML с сервера без проблем, и я создал UITableView для отображения ячеек. Однако я не знаю, как добавить ячейки в таблицу. Я посмотрел на insertRowsAtIndexPaths, но я не уверен, как его использовать? Как я понимаю, insertRowsAtIndexPaths принимает два параметра:Добавление программ программно в UITableView

NSArray, содержащий строку, в которой ячейка должна находиться и в каком разделе. Проблема заключается в том, что мое приложение будет иметь динамическое количество строк. Как я могу создать NSArray, если не знаю, сколько строк у меня будет? Можно ли использовать NSMutableArray?

Второй параметр, который требуется, - это анимация - это довольно просто.

Другая проблема, с которой я сталкиваюсь, - это где я действительно создаю ячейки? Как вы передаете ячейки в таблицу?

Я пробовал читать документацию, но это просто не кажется очень ясным! Вот код, у меня есть на данный момент внутри метода loadview контроллера вида:

//Before this I get the XML from the server so I am ready to populate 
//cells and add them to the table view 
NSArray *cells = [NSArray arrayWithObjects: 
        [NSIndexPath indexPathForRow:0 inSection:0], 
        [NSIndexPath indexPathForRow:1 inSection:0], 
        [NSIndexPath indexPathForRow:2 inSection:0], 
        [NSIndexPath indexPathForRow:3 inSection:0], 
        [NSIndexPath indexPathForRow:4 inSection:0], 
        [NSIndexPath indexPathForRow:5 inSection:0], 
        [NSIndexPath indexPathForRow:6 inSection:0], 
        [NSIndexPath indexPathForRow:7 inSection:0], 
        [NSIndexPath indexPathForRow:8 inSection:0], 
        [NSIndexPath indexPathForRow:9 inSection:0], 
        [NSIndexPath indexPathForRow:10 inSection:0], 
        [NSIndexPath indexPathForRow:11 inSection:0], 
        [NSIndexPath indexPathForRow:12 inSection:0], 
        nil]; 
[eventTypesTable beginUpdates]; 
[eventTypesTable insertRowsAtIndexPaths:cells withRowAnimation:UITableViewRowAnimationNone]; 
[eventTypesTable endUpdates]; 

ответ

18

Я думаю, что Вы приближаетесь это от неправильного направления. UITableViews не работают так, как вы ожидаете. insertRowsAtIndexPaths предназначен для вставки новых строк в таблицу, а не для заполнения ее в первом экземпляре.

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

Я бы порекомендовал вам начать чтение учебника, такого как этот: http://www.iosdevnotes.com/2011/10/uitableview-tutorial/, который выглядит довольно подробно для меня. В нем объясняется, как установить источник данных для таблицы и как вы можете настроить способ представления ваших данных в UITableView.

Удачи вам!

+0

Спасибо, я вижу, я был совершенно смущен о том, что работал. Мне удалось корректно выводить ячейки, но у меня проблема. Я извлекаю 12 строк из базы данных, однако экран только подходит 7. Когда экран заполнен и в симуляторе, если я попытаюсь прокрутить вниз, я получаю сообщение об ошибке в 'NSString * sEventType = [[eventTypes valueForKeyPath: @" name .text "] objectAtIndex: indexPath.row];' внутри метода cellForRowAtIndexPath. Есть что-то, чего я не хватает? Как я должен добавить контроллер прокрутки или что-то еще? Еще раз спасибо за быстрый и полезный ответ! – KerrM

+7

Ссылка не работает. Вот почему вы должны хотя бы опубликовать некоторый пример кода вместо того, чтобы полагаться на внешние ссылки. –

+0

ссылка не работает, но вы можете найти содержание этого URL-адреса здесь: http://web.archive.org/web/20150928131750/http://www.iosdevnotes.com/2011/10/uitableview-tutorial/ – Upsilon42

0

Вам не о чем беспокоиться. ячейки будут созданы автоматически. просто посмотрите на эти UITableview Class Reference

Tableview_iPhone

Вы должны осуществлять UITableView DataSource и протокол делегата. Также посмотрите на этот учебник UITableview Tutorial

16

Не нужно использовать insertRowsAtIndexPaths.

Проверил: UITableViewDataSource Protocol Reference и UITableView Class Reference

Магия происходит между этими тремя методами (методы протокола UITableViewDataSource):

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; 

Вам просто нужно заполнить массив. Да, это может быть NSMutableArray.

Вы можете заполнить массив в - (void)viewDidLoad, например:

yourItemsArray = [[NSMutableArray alloc] initWithObjects:@"item 01", @"item 02", @"item 03", nil]; 

И они используют методы источника данных, как это:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    // If You have only one(1) section, return 1, otherwise you must handle sections 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // Return the number of rows in the section. 
    return [yourItemsArray count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

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

    // Configure the cell... 
    cell.textLabel.text = [NSString stringWithFormat:[yourItemsArray objectAtIndex:indexPath.row]]; 

    return cell; 
} 

Как этой ячейки будет создана автоматически.

Если Вы Ставить в массив, просто нужно позвонить:

[self.tableView reloadData]; 
+0

Спасибо для вашего ответа, мне хотелось бы выбрать более одного ответа в качестве принятого. – KerrM

+3

Все в порядке, есть разные подходы к одной и той же проблеме. И если вы начинаете учиться, вы должны взять уроки, чтобы понять, как все работает, а не только код. Но оба действительно помогают – Frade

+0

Да, я думаю, что будет. Я столкнулся с другой проблемой, хотя, надеюсь, вы можете помочь - я извлекаю 12 строк из базы данных, однако экран подходит только для 7. Когда экран заполнен и в симуляторе, если я попытаюсь прокрутить вниз, я получаю ошибка в NSString * sEventType = [[eventTypes valueForKeyPath: @ "name.text"] objectAtIndex: indexPath.row]; внутри метода cellForRowAtIndexPath. Это почти похоже на то, что этот метод перестанет работать, как только он попадет в нижнюю часть экрана. Это что-то я сделал неправильно? – KerrM

2
//######## Adding new section programmatically to UITableView ############ 

    @interface MyViewController : UIViewController<UITableViewDataSource,UITableViewDelegate> 
    { 
     IBOutlet UITableView *tblView; 
     int noOfSection; 
    } 
    -(IBAction)switchStateChanged:(id)sender; 
    @end 



    @implementation MyViewController 
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{ 
     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
     if (self) { 
      // Custom initialization 
     } 
     return self; 
    } 
    - (void)viewDidLoad{ 
     [super viewDidLoad]; 

     noOfSection = 2; 
    } 
    - (void)viewDidUnload{ 
     [super viewDidUnload]; 
    } 
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{ 
     if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { 

      return YES; 
     } 

     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); 
    } 
    #pragma mark - TableView Delegate Methods 
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 
     return noOfSection; 
    } 
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 

     return 1; 
    } 
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 
     if(indexPath.section == 2){ 
      return 200; 
     } 
     return 50; 
    } 

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 

     static NSString *CellIdentifier = @"Cell"; 

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if (cell == nil) { 
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 

      UISwitch *switchBtn = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 20, 10)]; 
      cell.accessoryView = switchBtn; 

      [switchBtn addTarget:self action:@selector(switchStateChanged:) forControlEvents:UIControlEventValueChanged]; 
      cell.textLabel.font = [UIFont systemFontOfSize:14]; 
      cell.detailTextLabel.font = [UIFont systemFontOfSize:11]; 
      cell.textLabel.numberOfLines = 2; 
      cell.detailTextLabel.numberOfLines = 2; 
     } 



     if(indexPath.section == 0){ 
      cell.textLabel.text = @"Cell-1 Text"; 
      cell.detailTextLabel.text = @"Cell-1 Detail text"; 
     } 
     else if(indexPath.section == 1){ 
      cell.textLabel.text = @"Cell-2 Text"; 
     } 
     else { // new added section code is here... 
      cell.textLabel.text = @"New Added section"; 
     } 
     [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; 
     return cell; 
    } 
    -(IBAction)switchStateChanged:(id)sender{ 
     UISwitch *switchState = sender; 

     if(switchState.isOn == YES){ 
      NSLog(@"ON"); 
      NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:2]; 
      [self insertNewSectionWithIndexPath:indexPath]; 
     } 
     else { 
      NSLog(@"OFF"); 
      [self removeSectionWithIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]]; 
     } 
    } 
    -(void)insertNewSectionWithIndexPath:(NSIndexPath *)indexPath{ 


     noOfSection = 3; 
     [tblView insertSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationFade]; 
    } 
    -(void)removeSectionWithIndexPath:(NSIndexPath *)indexPath{ 
     noOfSection = 2; 
     [tblView deleteSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationFade]; 
    } 
    @end 
Смежные вопросы