问题
I want to create a new UIView on button click programmatically in cocos2d. Kindly help me with some sample code. Thanks in advance.
回答1:
You have to create a button like-
UIButton* myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(30, 70,100,38); //set frame for button
[myButton setTitle:@"subview" forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside];
Or you can use CCMenu as a button.
And then write the event handling function-
-(void)buttonClicked:(id)sender
{
UIView *myview=[[UIView alloc] initWithFrame: CGRectMake(0, 0,320,480)];
myview.backgroundColor=[UIColor redColor];
[[[CCDirector sharedDirector] openGLView] addSubview:myview];
[myview release];
}
}
回答2:
As you wrote above, the class is called UIView. It's really simple to create a new View. Take a look at this code snippet.
-(void)youButtonAction:(id)sender {
//This method is executed as soon as you button is pressed.
UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
[anotherView addSubview:newView]; //Add the newView to another View
[newView release];
}
I hope you got the point. At first you have to create the view, than add it to another view and in the end release it. ;-)
Sandro Meier
来源:https://stackoverflow.com/questions/4568424/how-to-create-a-new-uiview-programmatically-in-cocos2d