Добавьте текст из UITextField в NSMutableArray и отобразите его в UITableView - PullRequest
1 голос
/ 03 марта 2012

Я только начинаю с Objective-C для написания приложений для iPhone.Я прочитал пару книг и сделал несколько проектов с книгами, но я просто еще не эксперт.Я пытаюсь добавить текст из UITextField в NSMutableArray, а затем отобразить его в UITableView.Я знаю, что это действительно базовые вещи для большинства из вас, но я только начинающий.Пока у меня есть два файла: TableViewController.h:

#import <UIKit/UIKit.h>
@class AddItemViewController;

@interface TableViewController : UITableViewController {
    AddItemViewController *addItemViewController;
    NSMutableArray *itemsArray;

}
-(IBAction)addNewItem:(id)sender;
@property (nonatomic, retain)NSMutableArray *itemsArray;
@end

TableViewController.m

#import "TableViewController.h"
#import "AddItemViewController.h"


@implementation TableViewController
@synthesize itemsArray;

-(id)init
{
    [super initWithStyle:UITableViewStyleGrouped];

itemsArray = [[NSMutableArray alloc] init];

[self setTitle:@"Playing Around"];

UIBarButtonItem *bbi = [[UIBarButtonItem alloc]
                        initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewItem:)];
[[self navigationItem] setLeftBarButtonItem:bbi];
[bbi release];
return self;
}

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

#pragma mark Actions

-(IBAction)addNewItem:(id)sender
{
addItemViewController  = [[AddItemViewController alloc] init];
[UIView beginAnimations:@"animations" context:nil];
[[self navigationController] pushViewController:addItemViewController animated:NO];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO]; 
[UIView setAnimationDuration:0.7];
[UIView commitAnimations];


}

#pragma mark TableView Things

-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
return [itemsArray count];
}

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
static NSString *CellIdentifier = @"ItemCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    [cell autorelease];
}
cell.textLabel.text = [itemsArray objectAtIndex:indexPath.row];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
return cell;

}

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

// Release any cached data, images, etc. that aren't in use.
}

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


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


@end

AddItemViewController.h

#import <UIKit/UIKit.h>
@class TableViewController;


@interface AddItemViewController : UIViewController {
TableViewController *tableViewController;
IBOutlet UITextField *textField;
NSString *value;

}
-(IBAction)cancel:(id)sender;
-(IBAction)create:(id)sender;
@property (nonatomic, copy) NSString *value;
@property (nonatomic, retain)NSMutableArray *itemsArray;

@end

AddItemViewController.m

#import "AddItemViewController.h"
#import "TableViewController.h"


@implementation AddItemViewController
@synthesize value, itemsArray;

-(id)init
{
[self setTitle:@"Add Item"];
UIBarButtonItem *item;
item = [[UIBarButtonItem alloc]
                         initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel:)];
[[self navigationItem] setLeftBarButtonItem:item];
[item release];
item = [[UIBarButtonItem alloc]
                         initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(create:)];
[[self navigationItem] setRightBarButtonItem:item];
[item release];
return self;
}

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

-(void)viewDidUnload:(BOOL)animated
{
[super viewDidUnload];
[textField release];
textField = nil;
}

#pragma mark Actions

-(IBAction)cancel:(id)sender
{
tableViewController = [[TableViewController alloc] init];
[UIView beginAnimations:@"animations" context:nil];
[[self navigationController] pushViewController:tableViewController animated:NO];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO];
[UIView setAnimationDuration:0.7];
[UIView commitAnimations];


}

-(IBAction)create:(id)sender
{
    //This is where I get lost
NSString *string = [textField text];
NSLog(@"The string is: %@", string);
[itemsArray addObject:string];
[[tableViewController tableView] reloadData];

NSLog(@"The items are: %@", itemsArray);

tableViewController = [[TableViewController alloc] init];
[UIView beginAnimations:@"animations" context:nil];
[[self navigationController] pushViewController:tableViewController animated:NO];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO];
[UIView setAnimationDuration:0.7];
[UIView commitAnimations];
}

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


@end

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

Что мне теперь делать?Я получил это далеко, но текст из UITableView не будет отображаться, когда я пытаюсь добавить его в itemsArray.Любые советы будут великолепны!Заранее спасибо.

1 Ответ

0 голосов
/ 03 марта 2012

Ваш UITableView нуждается в источнике данных.Ваш контроллер табличного представления должен реализовывать протокол UITableViewDataSource. Вот документы .

...