How, where to declare unspecified identifier? - objective-c

Have the following code:
#import "UsingViewsViewController.h"
#implementation UsingViewsViewController
#synthesize pageControl;
#synthesize imageView1, imageView2;
- (void)dealloc
{
[pageControl release];
[imageView1 release];
[imageView2 release];
[super dealloc];
}
- (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.
}
#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
// --- initialize the first imageview to display an image---
[imageView1 setImage:[UIImage imageNamed:#"iMac_old.jpeg"]];
tempImageView = imageView2;
//--- make the first imageview visible and hide the second---
[imageView1 setHidden:NO];
[imageView2 setHidden:YES];
//--- Add the event handler for the page controller ---
[pageControl addTarget:self
action:#selector(pageTurning:)
forControlEvents:UIControlEventValueChanged];
/*
UIActionSheet *action =
[[UIActionSheet alloc]
initWithTitle:#"Title of action sheet"
delegate:self
cancelButtonTitle:#"OK"
destructiveButtonTitle:#"Delete message"
otherButtonTitles:#"Option 1",#"Option 2", nil];
[action showInView:self.view];
[action release];
*/
/*
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Hello"
message:#"This is an alert view"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:#"Option 1", #"Option 2", nil];
[alert show];
[alert release];*/
[super viewDidLoad];
}
//--- When the page controls value is changed---
- (void)pageTurning: (UIPageControl *)pageController {
//--- get the page number you can turning to ---
NSInteger nextPage = [pageController currentPage];
switch (nextPage) {
case 0:
[tempImageView setImage:
[UIImage imageNamed:#"iMac_old.jpeg"]];
break;
case 1:
[tempImageView setImage:
[UIImage imageNamed:#"iMac.jpeg"]];
break;
case 2:
[tempImageView setImage:
[UIImage imageNamed:#"Mac8100.jpeg"]];
break;
case 3:
[tempImageView setImage:
[UIImage imageNamed:#"MacPlus.jpeg"]];
break;
case 4:
[tempImageView setImage:
[UIImage imageNamed:#"MacSE.jpeg"]];
break;
default:
break;
}
//--- Switch the two imageviews---
if (tempImageView.tag==0) {
//--- imageView1---
tempImageView = imageView2;
bgImageView = imageView1;
}
else {
//---imageView2---
tempImageView = imageView1;
bgImageView = imageView2;
}
//---animate the two views flipping---
[UIView beginAnimations:#"flipping view"
context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:tempImageView];
cache:YES];
[tempImageView setHidden:YES];
[UIView commitAnimations];
[UIView beginAnimations:#"flipping view"
context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:tempImageView];
cache:YES];
[bgImageView setHidden:NO];
[UIView commitAnimations];
}
/*
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
NSLog(#"%d", buttonIndex);
}
*/
/*
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
NSLog(#"%d", buttonIndex);
}
*/
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
My problem is that Xcode is telling me that tempImageView is an unspecified identifier and won't compile.
Does it need to be declared as a variable? If so, where should I declare it, and what type should it be? Does it need to be declared in the header file too?
Thanks in advance.

you need to declare that variable.
In your .h file add:
(in your interfase)
UIImageView *tempImageView;
then in your .m file edit this line: #synthesize imageView1, imageView2;
change it to: #synthesize imageView1, imageView2, tempImageView ;
Hope it helps!
UPDATE
Forgot memory related stuff.. Add in your - (void)dealloc:
[imageView2 release];
[tempImageView release]; //ADD THIS LINE
[super dealloc];
UPDATE
Do the same with bgImageView
In your .h file add:
(in your interfase)
UIImageView *bgImageView;
then in your .m file edit this line: #synthesize imageView1, imageView2, tempImageView;
change it to: #synthesize imageView1, imageView2, tempImageView, bgImageView;
Add in your - (void)dealloc:
[imageView2 release];
[tempImageView release];
[bgImageView release]; //ADD THIS LINE
[super dealloc];

Related

AdMob integration destorts the Hello World Label text

I have created a simple hello world project for cocos2d-x 3.2. Added AdMob banner. The essence of adding banner is to create a view, then add into that view first the cocos2d-x content and then banner content:
UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self addChildViewController:_contentController];
[contentView addSubview:_contentController.view];
[_contentController didMoveToParentViewController:self];
[contentView addSubview:_bannerView];
self.view = contentView;
The result is that on iPhone, iPhone Retina, iPad Retina (but not in iPad) the Hello World text is distorted like this:
At the same time that stats text is not distorted:
I cannot understand what happens and why. Here is my full code:
.hfile
#import <UIKit/UIKit.h>
#interface BannerViewController : UIViewController
- (instancetype)initWithContentViewController:(UIViewController *)contentController;
- (void) hideBanner;
- (void) showBanner;
#end
and hers is .mm file
#import "BannerViewController.h"
#import "GADBannerView.h"
#interface BannerViewController () <GADBannerViewDelegate>
#end
#implementation BannerViewController {
GADBannerView *_bannerView;
UIViewController *_contentController;
Boolean _bannerLoaded;
}
- (instancetype)initWithContentViewController:(UIViewController *)contentController
{
self = [super init];
if (self != nil) {
// use kGADAdSizeBanner for a small banner in iPad
_bannerView = [[GADBannerView alloc] initWithAdSize: kGADAdSizeSmartBannerPortrait]; // scaled banner dependent on device size
_bannerView.adUnitID = #"ca-app-pub-874958723945898/8247587858";
_bannerView.delegate = self;
_contentController = contentController;
_bannerLoaded = NO;
}
return self;
}
- (void)loadView
{
UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self addChildViewController:_contentController];
[contentView addSubview:_contentController.view];
[_contentController didMoveToParentViewController:self];
[contentView addSubview:_bannerView];
self.view = contentView;
}
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_6_0
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return [_contentController shouldAutorotateToInterfaceOrientation:interfaceOrientation];
}
#endif
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return [_contentController preferredInterfaceOrientationForPresentation];
}
- (NSUInteger)supportedInterfaceOrientations
{
return [_contentController supportedInterfaceOrientations];
}
// For animation
- (void)viewDidLayoutSubviews
{
CGRect contentFrame = self.view.bounds;
CGRect bannerFrame = CGRectZero;
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_6_0
bannerFrame = _bannerView.frame;
#else
bannerFrame.size = [_bannerView sizeThatFits:contentFrame.size];
#endif
bannerFrame.origin.x = (contentFrame.size.width - bannerFrame.size.width) / 2;
if (_bannerLoaded) {
//contentFrame.size.height -= bannerFrame.size.height;
bannerFrame.origin.y = contentFrame.size.height - bannerFrame.size.height;
} else {
bannerFrame.origin.y = contentFrame.size.height;
}
_contentController.view.frame = contentFrame;
_bannerView.frame = bannerFrame;
}
- (void)viewDidLoad {
[super viewDidLoad];
_bannerView.rootViewController = self;
[self.view addSubview:_bannerView];
GADRequest *request = [GADRequest request];
[_bannerView loadRequest:request];
}
- (void)adViewDidReceiveAd:(GADBannerView *)bannerView
{
NSLog(#"adViewDidReceiveAd");
_bannerLoaded = YES;
[UIView animateWithDuration:0.25 animations:^{
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
}];
}
- (void)adView:(GADBannerView *)view didFailToReceiveAdWithError:(GADRequestError *)error
{
NSLog(#"adView didFailToReceiveAdWithError");
_bannerLoaded = NO;
[UIView animateWithDuration:0.25 animations:^{
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
}];
}
- (void) hideBanner{
//TODO:
}
- (void) showBanner{
//TODO:
}
- (void)dealloc {
_bannerView.delegate = nil;
[_bannerView release];
[super dealloc];
}
#end
// </GADBannerViewDelegate>
And I use it in AppController.mm like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Add the view controller's view to the window and display.
window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
// Init the CCEAGLView
CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [window bounds]
pixelFormat: kEAGLColorFormatRGBA8
depthFormat: GL_DEPTH24_STENCIL8_OES
preserveBackbuffer: NO
sharegroup: nil
multiSampling: NO
numberOfSamples: 0];
// Use RootViewController manage CCEAGLView
_viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
_viewController.wantsFullScreenLayout = YES;
_viewController.view = eaglView;
_bannerViewController = [[BannerViewController alloc] initWithContentViewController:_viewController];
// Set RootViewController to window
if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)
{
// warning: addSubView doesn't work on iOS6
[window addSubview: _bannerViewController.view];
//[window addSubview: _viewController.view];
}
else
{
// use this method on ios6
[window setRootViewController:_bannerViewController];
// [window setRootViewController:_viewController];
}
[window makeKeyAndVisible];
[[UIApplication sharedApplication] setStatusBarHidden:true];
// IMPORTANT: Setting the GLView should be done after creating the RootViewController
cocos2d::GLView *glview = cocos2d::GLView::createWithEAGLView(eaglView);
cocos2d::Director::getInstance()->setOpenGLView(glview);
cocos2d::Application::getInstance()->run();
return YES;
}
What is wrong here?
I have found the problem. I appears that there is a time in hours written with black color like in the image, which on on the Hello World label and hence it distorts:
The time is shown is simulators status bar. In order to hide it I added this:
//fix not hide status on ios7
- (BOOL)prefersStatusBarHidden
{
return YES;
}
into BannerViewController class and that's it!

iAd Banner Error "Too many instances of iAd"

I have an ad banner view on one my view controllers that acts as an instructional page for my game. When that view controller has been loaded multiple times I receive the following error.
WARNING: More than 10 instances of ADBannerView or ADInterstitialView currently exist. This is a misuse of the iAd API, and ad performance will suffer as a result. This message is printed only once.
I have searched this error on stackoverflow, read the responses but nothing has worked for me. I have read that you are meant to release the ad banner and then nil it etc. which I have and still am receiving this error. The code for my "viewWillAppear" and "viewWillDissapear" is below. Any help will be appreciated!
-(void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
_adBanner = [[ADBannerView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, 320, 50)];
_adBanner.delegate = self;
[self.view addSubview:_adBanner];
}
-(void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if (_adBanner != nil) {
_adBanner.delegate = nil;
_adBanner.hidden = YES;
[_adBanner release];
_adBanner = nil;
}
}
Try removing the iAd from its superview before setting it to nil:
-(void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if (_adBanner != nil) {
[_adBanner removeFromSuperview]; // <-new line
_adBanner.delegate = nil;
_adBanner.hidden = YES;
[_adBanner release];
_adBanner = nil;
}
Here is the code for iAd that I am already using in my apps with no problems:
implementation ViewController
{
ADBannerView *adView;
BOOL bannerIsVisible;
}
- (void)viewDidLoad
{
[super viewDidLoad];
adView = [[ADBannerView alloc] initWithFrame:CGRectZero];
adView.frame = CGRectOffset(adView.frame, 0, -50);
adView.requiredContentSizeIdentifiers = [NSSet setWithObject:ADBannerContentSizeIdentifier320x50];
adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier320x50;
[self.view addSubview:adView];
adView.delegate=self;
bannerIsVisible=NO;
}
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
if (!bannerIsVisible)
{
[UIView beginAnimations:#"animateAdBannerOn" context:NULL];
// banner is invisible now and moved out of the screen on 50 px
banner.frame = CGRectOffset(banner.frame, 0, 50);
[UIView commitAnimations];
bannerIsVisible = YES;
}
}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
if (bannerIsVisible)
{
[UIView beginAnimations:#"animateAdBannerOff" context:NULL];
// banner is visible and we move it out of the screen, due to connection issue
banner.frame = CGRectOffset(banner.frame, 0, -50);
[UIView commitAnimations];
bannerIsVisible = NO;
}
}
Instead of initializing the adBannerView in the individual class, create it in the AppDelegate.
I put:
#property (strong, nonatomic) ADBannerView *adBanner;
in my AppDelegate.h and:
self.adBanner = [[ADBannerView alloc] init];
in my AppDelegate.m
And then in the individual class I put:
#property (strong, nonatomic) ADBannerView *adBanner;
in the .h and in the .m I put:
{
BOOL _bannerIsVisible;
}
right below the #interface and in the #implementation I put:
#pragma mark Ads
- (WTMAppDelegate *) appdelegate {
return (WTMAppDelegate *)[[UIApplication sharedApplication] delegate];
}
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
NSLog(#"Retreieved Ad");
[self bringBannerBack];
}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
NSLog(#"Failed to retrieve ad");
[self moveBannerViewOffScreen];
}
- (void)bringBannerBack
{
[self.adBanner setAlpha:1];
[self.adBanner setNeedsDisplay];
[UIView beginAnimations:#"MoveView" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIView setAnimationDuration:0.1];
self.adBanner.frame = CGRectMake(0, self.view.bounds.size.height - 50, 320, 50);
[UIView commitAnimations];
_bannerIsVisible = YES;
[self.adBanner setAlpha:1];
}
//Move the banner off the screen.
- (void)moveBannerViewOffScreen
{
[self.adBanner setAlpha:0];
[self.adBanner setNeedsDisplay];
_bannerIsVisible = NO;
}
and in the viewWillAppear and ViewWillDisappear:
- (void) viewWillDisappear:(BOOL)animated{
self.adBanner.delegate=nil;
self.adBanner=nil;
[self.adBanner removeFromSuperview];
}
- (void) viewWillAppear:(BOOL)animated
{
self.adBanner = [[self appdelegate] adBanner];
self.adBanner.delegate = self;
[self.view addSubview:self.adBanner];
if (self.adBanner.bannerLoaded == NO){
NSLog(#"NO initial banner loaded");
[self moveBannerViewOffScreen];
} else {
NSLog(#"Initial ad loaded");
[self bringBannerBack];
}
}

popViewControllerAnimated affects viewwillappear?

I have two classes. lets say A,B Classes. from A class pushviewController is called, then B class will appear. Then here is the problem .when i call popviewcontrolleranimated method from B class it is going back to A, but then both class`s viewwillappear method is being called. so anyone can tell me what is going on in here. i am stuck!.
Below is the A class.
#implementation ShakeViewController
- (id) init {
if (self = [super init]) {
movieName = #"04";
self.view = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
[self.view setBackgroundColor:[UIColor whiteColor]];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"shake_it.png"]];
[self.view addSubview:imageView];
[imageView release];
nextController = [[OtsugeViewController alloc] init];
}
return self;
}
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
const float violence = 1.2;
static BOOL beenhere;
BOOL shake = FALSE;
if (beenhere) return;
beenhere = TRUE;
if (acceleration.x > violence || acceleration.x < (-1* violence))
shake = TRUE;
if (acceleration.y > violence || acceleration.y < (-1* violence))
shake = TRUE;
if (acceleration.z > violence || acceleration.z < (-1* violence))
shake = TRUE;
if (shake && mPlayerPushed) {
[self playSound:#"suzu"];
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"noVib"] == NO) {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
[[UIAccelerometer sharedAccelerometer] setDelegate:nil];
[self presentModalViewController:mMoviePlayer animated:YES];
[self play];
mPlayerPushed = YES;
}
beenhere = false;
}
- (void)toNext {
NSLog(#"ShakeViewController:toNext");
[self.navigationController pushViewController:nextController animated:NO];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSLog(#"Shake:viewWillAppear");
}
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
[[UIAccelerometer sharedAccelerometer] setDelegate:self];
[[UIAccelerometer sharedAccelerometer] setUpdateInterval:0.5];
}
- (void)dealloc {
[super dealloc];
}
#end
here is B class
#implementation OtsugeViewController
- (id) init {
if (self = [super init]) {
movieName = #"03";
self.view = [[[OtsugeView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
}
return self;
}
- (void) toNext {
NSLog(#"OtsugeViewController:toNext");
[self.navigationController popViewControllerAnimated:NO];
}
- (void) toToppage
{
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:NO];
[self.navigationController popToRootViewControllerAnimated:NO];
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(#"Screen touch Otsuge View");
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:self
cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil
otherButtonTitles:#"Retry", #"Main Menu", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
actionSheet.cancelButtonIndex = 0;
[actionSheet showInView:self.view];
[actionSheet release];
}
- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex: (NSInteger)buttonIndex
{
switch (buttonIndex) {
case 0: // Retry
[self presentModalViewController:mMoviePlayer animated:YES];
[self play];
break;
case 1: // Main Menu
[self toToppage];
break;
case 2: // Cancel
break;
default:
break;
}
}
- (void) viewWillAppear:(BOOL)animated {
mMoviePlayer.moviePlayer.backgroundView.backgroundColor = [UIColor blackColor];
[self playSound:#"taiko_1"];
NSLog(#"Otsuge:viewWillAppear");
[(OtsugeView *)self.view renewImageView];
[super viewWillAppear:animated];
}
- (void) viewDidAppear:(BOOL)animated{
NSLog(#"Otsuge:viewDidAppear");
[super viewDidAppear:animated];
}
- (void) dealloc {
[super dealloc];
}
#end
It's normal. View will appear is called each time a view will appear. If you want to call a method only when the view appears for the first time use -viewdidload because in a view controller each view that is in the stack is kept in memory but those you pop get deallocated.

Add text from UITextField to NSMutableArray and display it in UITableView

I am just starting with Objective-C to write iPhone apps. I read a couple books and made some projects with the books, but I am just not an expert yet. I am trying to add some text from a UITextField to an NSMutableArray and then display it in a UITableView. I know this is really basic stuff for most of you, but I am just a beginner. So far I have two files:
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
(Sorry I put the whole thing here, but for all I know I could be doing something wrong in any part of this.)
So if you want to skip most of the stuff I think I did right just go to the create: method.
Now what do I do? I got this far, but the text from the UITableView will not show up when I try to add it to the itemsArray. Any tips would be great! Thanks in advance.
Your UITableView needs a data source. Your table view controller should implement the UITableViewDataSource protocol. Here are the docs.

UITextField Example in Cocos2d

Can anyone please suggest some links for using UITextField in cocos2d.
I want to press on label, then the UITextField should get selected and I need to edit on that UITextField.
I'm doing this in a current project to allow for entering the number of the level to start playing at, so that's why my variables and methods are named the way they are; you should probably adjust these to make sense for you.
In your app controller, define this as an instance variable:
UITextField *levelEntryTextField;
Create it inside applicationDidFinishLaunching:
levelEntryTextField = [[UITextField alloc] initWithFrame:
CGRectMake(60, 165, 200, 90)];
[levelEntryTextField setDelegate:self];
Define a method to activate the text field. You should also declare it in the header file for your app controller.
- (void)specifyStartLevel
{
[levelEntryTextField setText:#""];
[window addSubview:levelEntryTextField];
[levelEntryTextField becomeFirstResponder];
}
This will make pressing "return" on the keypad end editing
- (BOOL)textFieldShouldReturn:(UITextField*)textField {
//Terminate editing
[textField resignFirstResponder];
return YES;
}
This is triggered when the editing is actually done.
- (void)textFieldDidEndEditing:(UITextField*)textField {
if (textField==levelEntryTextField) {
[levelEntryTextField endEditing:YES];
[levelEntryTextField removeFromSuperview];
// here is where you should do something with the data they entered
NSString *result = levelEntryTextField.text;
}
}
Now to actually set things in motion, you put this somewhere. I call this from within one of my Scene classes, in response to a user action:
[[[UIApplication sharedApplication] delegate] specifyStartLevel];
I took the example that Jack provided and actually created a working project, this was done using the Cocos2D 0.7.1 XCode Template, and then just editting the *AppDelegate.m/.h files, which are provided below in there entirety. I also modified some of what Jack said, because I feel that creating the UITextField in the appDidFinishLoading would utilize a bit too much memory, especially if the text field is not used all the time ... this solution creates the text field only when it is needed, the sample draws an empty Cocos2D Layer scene, and on screen touch, it displays the text field for you to start entering text into. It will spit out the result of what you entered to the Console - you can pass this to whatever is necessary in your own code.
the .h
#import <UIKit/UIKit.h>
#import "cocos2d.h"
#interface MYSCENE : Layer <UITextFieldDelegate>
{
UITextField *myText;
}
-(void)specificStartLevel;
#end
#interface textFieldTestAppDelegate : NSObject <UIAccelerometerDelegate, UIAlertViewDelegate, UITextFieldDelegate, UIApplicationDelegate>
{
UIWindow *window;
}
#end
and then the .m
#import "textFieldTestAppDelegate.h"
#implementation MYSCENE
-(id) init
{
self = [super init];
isTouchEnabled = YES;
return self;
}
-(BOOL)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self specifyStartLevel];
return kEventHandled;
}
-(void)specifyStartLevel {
myText = [[UITextField alloc] initWithFrame:CGRectMake(60, 165, 200, 90)];
[myText setDelegate:self];
[myText setText:#""];
[myText setTextColor: [UIColor colorWithRed:255 green:255 blue:255 alpha:1.0]];
[[[[Director sharedDirector] openGLView] window] addSubview:myText];
[myText becomeFirstResponder];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
[myText resignFirstResponder];
return YES;
}
-(void)textFieldDidEndEditing: (UITextField *)textField {
if(textField == myText) {
[myText endEditing:YES];
[myText removeFromSuperview];
NSString *result = myText.text;
NSLog([NSString stringWithFormat:#"entered: %#", result]);
} else {
NSLog(#"textField did not match myText");
}
}
-(void) dealloc
{
[super dealloc];
}
#end
#implementation textFieldTestAppDelegate
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[window setUserInteractionEnabled:YES];
[[Director sharedDirector] setDisplayFPS:YES];
[[Director sharedDirector] attachInWindow:window];
Scene *scene = [Scene node];
[scene addChild: [MYSCENE node]];
[window makeKeyAndVisible];
[[Director sharedDirector] runWithScene: scene];
}
-(void)dealloc
{
[super dealloc];
}
-(void) applicationWillResignActive:(UIApplication *)application
{
[[Director sharedDirector] pause];
}
-(void) applicationDidBecomeActive:(UIApplication *)application
{
[[Director sharedDirector] resume];
}
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
[[TextureMgr sharedTextureMgr] removeAllTextures];
}
#end
To add Text field in cocos2d as below code
first of all you add view in Scene and afetr add textfield add in view thats very easy.
-(id) init
{
if( (self=[super init]) )
{
// add view in scene
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 568)];
view.backgroundColor = [UIColor redColor];
// add textfield in view
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 140, 300, 30)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.font = [UIFont systemFontOfSize:15];
textField.placeholder = #"enter text";
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.delegate = self;
[view addSubview:textField];
// add view in scene
[[[CCDirector sharedDirector] view] addSubview:view];
}
return self;
}
you can also use CCTextfield in cocos2d best example is https://github.com/iNinja/CCTextField
Try the following CCNode subclass, CCMenuItemTextField, to use text fields in cocos2d.
The class is directly subclassed from CCMenuItemSprite. When tapped, the "selected" method is called and a UITextField is added to the main window. After editing is done, "unselected" method is called and the UITextField is removed from screen. User's input is saved to a CCLabelTTF node, which position itself exactly as the original UITextField.
CCMenuItemTextField.h
#interface CCMenuItemTextField : CCMenuItemSprite<UITextFieldDelegate> {
UITextField *textField_;
CCLabelTTF *label_;
CGFloat paddingLeft_;
}
#property (readonly, nonatomic) UITextField *textField;
#property (readonly, nonatomic) CCLabelTTF *label;
#property (assign, nonatomic) CGFloat paddingLeft;
- (void)selected;
- (void)unselected;
- (void)setFontSize:(CGFloat)size;
- (NSString*)text;
- (void)setText:(NSString*)text;
#end
CCMenuItemTextField.m
#import "CCMenuItemTextField.h"
#implementation CCMenuItemTextField
#synthesize
textField = textField_,
label = label_,
paddingLeft = paddingLeft_;
- (id)init
{
CCSprite *normalSprite = [CCSprite spriteWithFile:#"text_field_background.png"];
CCSprite *selectedSprite = [CCSprite spriteWithFile:#"text_field_background.png"];
CCSprite *disabledSprite = [CCSprite spriteWithFile:#"text_field_background.png"];
return [self initWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite];
}
- (id)initWithNormalSprite:(CCNode<CCRGBAProtocol> *)normalSprite
selectedSprite:(CCNode<CCRGBAProtocol> *)selectedSprite
disabledSprite:(CCNode<CCRGBAProtocol> *)disabledSprite
{
self = [super initWithNormalSprite:normalSprite
selectedSprite:selectedSprite
disabledSprite:disabledSprite
target:self
selector:#selector(selected)];
if (self) {
paddingLeft_ = 3.0;
textField_ = [[UITextField alloc] init];
[textField_ setTextColor:[UIColor blackColor]];
[textField_ setFont:[UIFont systemFontOfSize:18]];
label_ = [[CCLabelTTF node] retain];
[label_ setAnchorPoint:ccp(0,0.5)];
[label_ setFontSize:18];
[label_ setVisible:NO];
[label_ setColor:ccBLACK];
[self addChild:label_];
}
return self;
}
- (void)dealloc
{
[label_ release];
[textField_ release];
[super dealloc];
}
// --------------------------------
// Public
// --------------------------------
- (void)selected
{
[super selected];
[label_ setVisible:NO];
CGAffineTransform transform = [self nodeToWorldTransform];
float textFieldHeight = textField_.font.lineHeight;
float width = self.contentSize.width;
float height = self.contentSize.height;
float left = transform.tx + paddingLeft_;
float top = 480 - transform.ty - height + (height - textFieldHeight) / 2;
[textField_ setFrame:CGRectMake(left, top, width, height)];
[[[[CCDirector sharedDirector] view] window] addSubview:textField_];
[textField_ becomeFirstResponder];
[textField_ setDelegate:self];
}
- (void)unselected
{
[super unselected];
[label_ setVisible:YES];
[label_ setPosition:ccp(paddingLeft_, self.contentSize.height/2)];
NSString *text = textField_.text ? textField_.text : #"";
[label_ setString:text];
[textField_ resignFirstResponder];
[textField_ removeFromSuperview];
}
- (NSString*)text
{
return [label_ string];
}
- (void)setText:(NSString*)text
{
[label_ setString:text];
[textField_ setText:text];
}
// --------------------------------
// UITextFieldDelegate
// --------------------------------
- (BOOL)textFieldShouldReturn:(UITextField*)textField {
[self unselected];
return YES;
}
- (void)textFieldDidEndEditing:(UITextField*)textField {
[self unselected];
}
- (void)setFontSize:(CGFloat)size
{
[label_ setFontSize:size];
[textField_ setFont:[UIFont systemFontOfSize:size]];
}
// --------------------------------
// CCNode
// --------------------------------
- (void)onExitTransitionDidStart
{
[super onExitTransitionDidStart];
[self unselected];
}
#end