objective-c Cocos2d 中的 UITextField 示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/693483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:18:47  来源:igfitidea点击:

UITextField Example in Cocos2d

objective-ccocos2d-iphonetextfield

提问by Hyman Nutting

Can anyone please suggest some links for using UITextField in cocos2d. I want to press on label, then the UITextFieldshould get selected and I need to edit on that UITextField.

任何人都可以建议一些在 cocos2d 中使用 UITextField 的链接。我想按下标签,然后UITextField应该被选中,我需要编辑它UITextField

回答by Hyman Nutting

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:

在 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];

回答by David Higgins

I took the example that Hyman 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 Hyman 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.

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

the .h

.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

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

回答by Kirit Modi

To add Text field in cocos2d as below code

在 cocos2d 中添加文本字段如下代码

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

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

回答by Huan Li

Try the following CCNode subclass, CCMenuItemTextField, to use text fields in cocos2d.

试试下面的 CCNode 子类 CCMenuItemTextField,以在 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.

该类直接从 CCMenuItemSprite 继承。点击时,将调用“selected”方法并将 UITextField 添加到主窗口。编辑完成后,调用“unselected”方法并从屏幕中移除 UITextField。用户的输入被保存到一个 CCLabelTTF 节点,该节点将自身定位为与原始 UITextField 完全相同的位置。

CCMenuItemTextField.h

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

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