2009-03-28 15 views
12

¿Alguien puede sugerir algunos enlaces para usar UITextField en cocos2d. Quiero presionar en la etiqueta, luego el UITextField debe ser seleccionado y necesito editar en ese UITextField.UITextField Ejemplo en Cocos2d

Respuesta

15

Estoy haciendo esto en un proyecto actual para permitir el ingreso del número del nivel para comenzar a jugar, así que es por eso que mis variables y métodos se nombran tal como son; probablemente deberías ajustar esto para que tenga sentido para ti.

En el controlador de aplicación, definir esto como una variable de instancia:

UITextField *levelEntryTextField; 

crearlo dentro applicationDidFinishLaunching:

levelEntryTextField = [[UITextField alloc] initWithFrame: 
               CGRectMake(60, 165, 200, 90)]; 
    [levelEntryTextField setDelegate:self]; 

definir un método para activar el campo de texto. También debe declararlo en el archivo de encabezado para su controlador de aplicación.

- (void)specifyStartLevel 
{ 
    [levelEntryTextField setText:@""]; 
    [window addSubview:levelEntryTextField]; 
    [levelEntryTextField becomeFirstResponder];  
} 

Esto hará que la tecla "retorno" en la edición final teclado

- (BOOL)textFieldShouldReturn:(UITextField*)textField { 
    //Terminate editing 
    [textField resignFirstResponder]; 
    return YES; 
} 

Esto se activa cuando la edición se hace realmente.

- (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; 
    } 
} 

Ahora para realmente poner las cosas en movimiento, póngalo en alguna parte. A esto lo llamo desde el interior de una de mis clases de escena, en respuesta a una acción del usuario:

[[[UIApplication sharedApplication] delegate] specifyStartLevel]; 
+0

Hey, he tratado de esta manera pero sólo el teclado aparece. No vi el campo de texto – OMGPOP

+1

Pruebe [textBox setTextColor: [UIColor colorWithRed: 0 verde: 0 azul: 0 alfa: 1.0]]; [textBox setBackgroundColor: [UIColor colorWithRed: 255 verde: 255 azul: 255 alpha: 1.0]]; – RSH1

+0

¿Qué es 'window' en' specifyStartLevel'? OK para aquellos principiantes reales es la ventana '[[[CCDirector sharedDirector]]]]. – Claudiu

10

Tomé el ejemplo que Jack siempre y de hecho creó un proyecto de trabajo, esto se hizo usando la plantilla de Xcode 0.7.1 Cocos2D y luego solo edite los archivos * AppDelegate.m/.h, que se proporcionan a continuación en su totalidad. También modifiqué algo de lo que dijo Jack, porque creo que crear el UITextField en el appDidFinishLoading utilizaría demasiada memoria, especialmente si el campo de texto no se usa todo el tiempo ... esta solución crea el campo de texto solo cuando es necesario, la muestra dibuja una escena vacía de Cocos2D Layer, y en la pantalla táctil, muestra el campo de texto para que usted comience a ingresar texto. Escupirá el resultado de lo que ingresó en la consola; puede pasar esto a lo que sea necesario en su propio código.

el .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 

y luego el .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 
+0

gracias hermano. Bien hecho – OMGPOP

+0

Eso debería ser [[[[CCDirector sharedDirector] openGLView] ventana] addSubview: myText]; en lugar de la ventana [[[[Director sharedDirector] openGLView]] addSubview: myText]; –

0

intente lo siguiente subclase CCNode, CCMenuItemTextField, utilizar los campos de texto en cocos2d.

La clase se subclasifica directamente desde CCMenuItemSprite. Cuando se toca, se llama al método "seleccionado" y se agrega un UITextField a la ventana principal. Después de realizar la edición, se llama al método "no seleccionado" y se quita el UITextField de la pantalla. La entrada del usuario se guarda en un nodo CCLabelTTF, que se posiciona exactamente como el UITextField original.

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 
+1

¿Qué versión de Cocos2d usaste? Parece que no funciona directamente con v1.1. –

2

Para añadir campo de texto de la siguiente manera cocos2d código

en primer lugar se agrega en vista de escena y afetr campo de texto añadir añadir en vista de eso es muy fácil.

-(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; 
} 

también se puede utilizar en CCTextfield cocos2d mejor ejemplo es https://github.com/iNinja/CCTextField