Cocos2d 中的 UITextField 示例

发布于 2024-07-16 04:24:43 字数 127 浏览 7 评论 0原文

任何人都可以建议一些在 cocos2d 中使用 UITextField 的链接吗? 我想按标签,然后应该选择 UITextField 并且我需要在该 UITextField 上进行编辑。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

魂ガ小子 2024-07-23 04:24:43

我在当前的项目中这样做是为了允许输入开始玩的关卡编号,这就是我的变量和方法如此命名的原因; 您可能应该调整这些以使其对您有意义。

在您的应用程序控制器中,将其定义为实例变量:

  UITextField *levelEntryTextField;

在 applicationDidFinishLaunching 内创建它:

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

定义一个方法来激活文本字段。 您还应该在应用程序控制器的头文件中声明它。

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

这将使按键盘上的“返回”结束编辑。

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

实际完成编辑时会触发此操作。

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

现在要真正启动事情,你要把它放在某个地方。 我从我的一个场景类中调用它,以响应用户操作:

  [[[UIApplication sharedApplication] delegate] specifyStartLevel];

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];
你的他你的她 2024-07-23 04:24:43

我采用了 Jack 提供的示例并实际创建了一个工作项目,这是使用 Cocos2D 0.7.1 XCode 模板完成的,然后只需编辑 *AppDelegate.m/.h 文件,这些文件在下面完整提供。 我还修改了 Jack 所说的一些内容,因为我觉得在 appDidFinishLoading 中创建 UITextField 会占用太多内存,特别是如果文本字段不是一直使用的话......这个解决方案仅在它时才创建文本字段需要时,该示例绘制一个空的 Cocos2D Layer 场景,并在屏幕触摸时显示文本字段,供您开始输入文本。 它将输出您在控制台中输入的内容的结果 - 您可以将其传递给您自己的代码中所需的任何内容。

.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

,然后是 .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

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
‖放下 2024-07-23 04:24:43

要在 cocos2d 中添加文本字段,如下代码所示,

首先在场景中添加视图,然后在视图中添加文本字段,这非常简单。

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

您还可以在 cocos2d 中使用 CCTextfield 最好的例子是 https://github.com/iNinja/CCTextField

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

层林尽染 2024-07-23 04:24:43

尝试使用以下 CCNode 子类 CCMenuItemTextField 在 cocos2d 中使用文本字段。

该类直接从 CCMenuItemSprite 派生出来。 点击时,将调用“selected”方法,并将 UITextField 添加到主窗口。 编辑完成后,调用“unselect”方法并将 UITextField 从屏幕上删除。 用户的输入被保存到 CCLabelTTF 节点,该节点的位置与原始 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文