Question

There are a lot of similar questions and answers, but they don't solve the main problem: how to properly add any text field in cocos2d with its workable delegate.

For example if I create UITextfield and simply add it to [[CCDirector sharedDirector] view] then it will call textFieldShouldReturn: method only. No more methods doesn't work, even textViewDidBeginEditing:

I gave the same result with using of separate view and UITextField. I also tried to create a separate UIViewController to use its view with UITextField but it even make my app falling down

Was it helpful?

Solution 2

My mistake was that UITextFieldDelegate and UITextViewDelegate have some similar mehods, and I used some methods from the second delegate. Example:

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView;
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;

Of course I wrote (UITextView *)textField at the end.

OTHER TIPS

1: Make sure your CCNode contains the UITextFieldDelegate:

@interface MyLayer : CCLayer <UITextFieldDelegate>

2: Init the UITextField as per usual:

UITextField *nameField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, fieldWidth, fieldHeight)];
            nameField.textAlignment = NSTextAlignmentCenter;
            nameField.font = [UIFont fontWithName:kFontName size:24];
            nameField.text = @"Enter Name";
            nameField.delegate = self;
            nameField.backgroundColor = [UIColor grayColor];
            nameField.textColor = [UIColor whiteColor];
            nameField.autocorrectionType = UITextAutocorrectionTypeNo;

3: Add the field to the CCDirector view:

[[[CCDirector sharedDirector] view] addSubview:nameField];

4: Implement the UITextField delegates in your CCNode:

- (BOOL)textFieldShouldReturn:(UITextField*)textField
- (void)textFieldDidBeginEditing:(UITextField *)textField
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top