Подтвердить что ты не робот

Добавление программ программно в UITableView

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

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];
4b9b3361

Ответ 1

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

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

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

Удачи!

Ответ 2

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

Проверьте: UITableViewDataSource Protocol Reference и Ссылка на класс UITableView

Магия происходит между этими тремя методами (методы протокола 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];

Ответ 3

//######## 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

Ответ 4

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

Tableview_iPhone

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