Как программно создать UITableView и заполнить NSArray в Xcode 4.2? - PullRequest
2 голосов
/ 04 января 2012

Я пытался понять разницу между раскадровками и кодированием в Objective-C.Похоже, что вы можете создать UITableView, перетаскивая объект в раскадровку или кодируя в новом представлении в Objective-C.

Проблема в том, что я хочу сохранить раскадровку как можно более тонкой.Поэтому я пытаюсь создать и заполнить UITableView NSArray из 5 строк.Мой код будет работать только на 1 строку перед возвратом ошибки компилятора ... Я собираюсь отбросить весь проект и начать все сначала.

Я был бы очень признателен, если кто-то знаком с новым Xcode 4.2 / iOS5 / Storyboardsможет предоставить разумное решение для построения UITableView.Я знаю, что это такая основная задача, поэтому с самого начала это так расстраивает.Я могу заставить Табличное Представление работать, но я не могу заставить Массив динамически заполнять и создавать #X количество строк ...

Дайте мне знать, если я могу предоставить больше информации.Я пытался быть максимально простым - просто нужно, чтобы TableView работал и заполнялся массивом:)

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

Ответы [ 2 ]

3 голосов
/ 04 января 2012

Причина сбоя заключается в том, что в раскадровке вы должны изменить табличное представление на динамические прототипы вместо статических ячеек.По какой-то причине статические ячейки являются настройками по умолчанию.Как только вы освоите раскадровки, это здорово, особенно когда дело касается просмотра таблиц.Ваш первоначальный вид настроен как NavigationController, в котором MasterviewController используется как RootViewController, поэтому он загружается как первый вид.Нажмите на TableView в MainStoryboard и замените Cels на Dynamic Prototypes, или он будет использовать статические, созданные вами прямо в раскадровке.Вы можете создавать собственные ячейки прямо на виде таблицы в раскадровке.Еще одна вещь, на которую следует обратить внимание, это то, что идентификатор повторного использования должен быть установлен на одно и то же имя в раскадровке и в TableViewController.Вы также можете просто увеличить количество статических ячеек до нужного вам числа, если знаете, что оно всегда будет одинаковым.

3 голосов
/ 04 января 2012

Вот тривиальный пример с подклассом UITableViewController, заполненный NSArray (NSMutableArray) из моего примера кода. Он не использует раскадровки, но вы сказали, что все нормально в вашем комментарии. Надеюсь, мой пример кода поможет вам.

Заголовок:

@interface MainTableViewController : UITableViewController 
{
    NSMutableArray *_items;
}

@end

Реализация:

@implementation MainTableViewController

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Lifetime
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) 
    {
        // datastore
        _items = [[NSMutableArray alloc] init];
        for (int index=0; index < 5; index++) 
        {
            [_items addObject:[NSString stringWithFormat:@"item #%d", index]];            
        }
    }
    return self;
}

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

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Table View DataSource
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // a typical table has one section
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // number of rows
    return [_items count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // NSIndexPath contains an array of indexes.  For UITableView:
    //    indexAtPosition:0 is the section number
    //    indexAtPosition:1 is the row number

    // create an identifier for this type of cell
    static NSString *CellIdentifier = @"Cell";

    // get a cell of this type from the re-use queue or create one
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) 
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Configure the cell...
    NSString *title = [_items objectAtIndex:[indexPath indexAtPosition:1]];
    [[cell textLabel] setText:title];
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];

    return cell;
}


// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    {
        // Delete the row from the data source
        NSLog(@"delete section: %d rol: %d", [indexPath indexAtPosition:0], [indexPath indexAtPosition:1]);
        [_items removeObjectAtIndex:[indexPath indexAtPosition:1]];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) 
    {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        NSLog(@"insert section: %d rol: %d", [indexPath indexAtPosition:0], [indexPath indexAtPosition:1]);        
    }   
}

// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    NSString *fromItem = [_items objectAtIndex:[fromIndexPath indexAtPosition:1]];
    [_items removeObjectAtIndex:[fromIndexPath indexAtPosition:1]];
    [_items insertObject:fromItem atIndex:[toIndexPath indexAtPosition:1]];
}

// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark UITableViewDelegate
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"selected section: %d rol: %d", [indexPath indexAtPosition:0], [indexPath indexAtPosition:1]);

    // get the selected cell
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];

    // navigate to detail
    DetailedTableViewController *detailedView = [[DetailedTableViewController alloc] init];
    [[self navigationController] pushViewController:detailedView animated:YES];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark View lifecycle
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    [[self navigationItem] setRightBarButtonItem: [self editButtonItem]];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

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

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

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

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

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
...