Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

objective c - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...