Below is a simple example of adding a UIKit Alert dialog and UITextField to a Cocos2d Scene. It turns out they play together quite well. The code below assumes you are in the "init" method of your Cocos2d Layer object. Normally, you would be adding Sprites, Labels, etc. here. But now, you want to add this dialog. Here is the code.....
- (id) init {
self = [super init];
if (self != nil) {
Sprite * bg = [Sprite spriteWithFile:@"blah.png"];
[bg setPosition:ccp(240, 160)];
[self addChild:bg z:0];
UIView* view = [[Director sharedDirector] openGLView];
NSString *score = [NSString stringWithFormat:@"You Scored: %d", gameScore];
UIAlertView* myAlertView = [[UIAlertView alloc] initWithTitle:score
message:@"High Score" delegate: self
cancelButtonTitle: @"Cancel" otherButtonTitles: @"OK", nil];
[view addSubview: myAlertView];
CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0.0, 75.0);
[myAlertView setTransform: myTransform];
nameField = [[UITextField alloc] initWithFrame:
CGRectMake(12.0, 45.0, 260.0, 25.0)];
[nameField setBackgroundColor: [UIColor whiteColor]];
nameField.text = @"Enter Name Here"s
nameField.clearsOnBeginEditing = true;
[myAlertView addSubview: nameField];
[myAlertView show];
[myAlertView release];
}
return self;
}
As you can see, you can get a UIView from the Cocos2d Director. Once you have that, you have entered the UIKit world. The only other trick is the "Transform" that is used to make sure the geometry is compatible. This works great for my app. There is a lot more to learn about mixing UIKit and Cocos2d. I hope to learn more in the future!
Where gameScore?
ReplyDelete