How to create a new UIView programmatically in cocos2d? - iphone

I want to create a new UIView on button click programmatically in cocos2d. Kindly help me with some sample code. Thanks in advance.

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

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

Related

Adding UIButtons to a Cocos2d project

In Cocos2d, I have read that
[[[[CCDirector sharedDirector] openGLView] window] addSubview:someButton];
will add a UIView to the main window: http://www.cocos2d-iphone.org/forum/topic/3588
Yet in my code I have this:
- (void)onEnterTransitionDidFinish {
UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
[[[[CCDirector sharedDirector] openGLView] window] addSubview:button];
}
But no button is visible. This method is part of a CCLayerColor which is the first scene presented in the app, if that matters. What am I doing wrong here? Thanks!
Edit: I can confirm that the buttons are being added to the windows subviews, because NSLogging
[[[[[CCDirector sharedDirector] openGLView] window] subviews] count]
shows a difference when I comment/uncomment the addSubview line. So why isn't the button showing up?
Edit 2:
Thanks to #Marine, I have found that my problem is the way I am declaring my button; using buttonWithType: solved the problem, because this code works:
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(100, 100, 100, 100)];
[[[[CCDirector sharedDirector] openGLView] window] addSubview:button];
Can someone explain to me why using this class method works and using initWithFrame: doesn't? Because I would rather not create lots of autoreleased objects, and also because I have some UIButton subclasses that do NOT show up when I use the buttonWithType: method.
Edit 3 (Solution):
The reason why using anything but buttonWithType: doesn't work is that if you do not use that method to create the button, the background color of the button is not set, and by default it is clearColor. Using [button setBackgroundColor:[UIColor redColor]] or any other color fixes the problem. Also, if using a custom button class like this one, you might need to manually call [button awakeFromNib] if the button isn't connected to a nib.
Try the below code it would help you
-(id) init
{
if((self = [super init]))
{
UIView* glView = (UIView*) [[CCDirector sharedDirector] openGLView];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setFrame:CGRectMake(100, 100, 250, 250)];
[btn addTarget:self action:#selector(actionper:) forControlEvents:UIControlEventTouchUpInside];
[glView addSubview:btn];
}
return self;
}
-(void) actionper : (id) sender
{
printf("\n Stuff of the Code on button Press");
}
I have posted the solution to the problem as an edit to the question.
Try using the bringsubviewtofront method of the OpenGL window passing the recently added button as the argument. Also make sure that the frame of your button is such that it is in the visible part of the screen. Try playing around with it's position.

Button click not working when in presence of single Tap gesture

I have view hierarchy as follows
MyViewController --> ScrollView(added via IB) --> ImageView (+ zooming there) ---> button added on image View(added via code)
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"map.png"]];
[scroll addSubview:imageView];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(660, 120, 40, 40);
[myButton setTitle:#"10" forState:UIControlStateNormal];
[myButton addTarget:self action:#selector(asiaPressed:) forControlEvents:UIControlEventTouchUpInside];
[myButton setEnabled:YES];
[imageView addSubview:myButton];
later on in view controller, i defined selector as
-(void) asiaPressed:(id)sender{
NSLog(#"asiaPressed clicked");
}
But it is never going inside selector..
Pls help...i guess it is very basic error..
Thanks in advance
UIImageView has userInteractionEnabled property set to NO by default so it (and its subviews) does not receive touch events. You need to set that property to YES manually:
...
imageView.userInteractionEnabled = YES;
...
P.S. You also mention gesture recognizer in question title, however have not posted any code with it - so if it present it may also cause the problems, but the problem is most likely is what I described above

Show a subview when button is pressed. (Something like view which appears when operating system Windows "start" button is pressed

I want to show a subview that will contain list of menu when a UIbutton is pressed. Should I use vertical SegmentControl?
Thanks for any help in advance
You don't have to use vertical TabbarViewController.
First of all, go to the interface builder and drag a Button, connect the Button to an action method you declare in the .m file
let's said that the method is
- (IBAction) btnHandler :(id)sender {
}
then declare a new view and add it to your main view
so the btnhandler method will look like this
- (IBAction) btnHandler :(id)sender {
UIView *subview = [[UIView alloc] initWithFrame:CGRectMake(0, 50, 320, 300)];
//here add what ever you want to the new created view using the
//[subview addSubview:(your Componant)];
[self.view addSubview:subview];
}
please forgive me if i made a mistake, this is not tested code. i write it now in the browser.
If its an iPad application, maybe consider calling a UIPopOverController
You could use an Action Sheet if you're aiming for a native iOS look and feel.
Agree with the previous answer that a pop over is a great option if this is an iPad app.
You could go full custom of course with your own viewController which you can animate in from the top or bottom depending on your need.
Option 1:
Design the view in your nib.
Option 2:
Have a separate view controller
You can use addSubView method to add the view when you press the UIButton
Try below code that will help you.
- (void)viewDidLoad {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.view addSubview:button];
[super viewDidLoad];
}
-(IBAction)buttonPressed:(id)sender
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, 200, 300, 100)];
view.backgroundColor = [UIColor clearColor];
view.backgroundColor = [UIColor grayColor];
[self.view addSubview:view];
}

iPhone custom navigation bar with button doesnt click

Ive got an iPhone/iPad universal application and I wanted to have a custom navigation bar where the top half of the nav bar contained our companies logos, and the bottom half was the standard navigation bar.
I figured out how to do this, showing in the code below, but my UIButton "logosButton" doesnt always respond to being clicked, it appears as though only certain parts of the button are active, and others dont do anything at all... I cannot figure out why this is.
- (void)viewDidLoad {
[super viewDidLoad];
[[self view] addSubview: navController.view];
float width = IS_IPAD ? 768.0f : 320.0f;
float logosHeight = IS_IPAD ? 20.0f : 20.0f;
float barHeight = IS_IPAD ? 32.0f : 32.0f;
self.navBar = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, logosHeight, width, barHeight)];
UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, logosHeight)];
UIButton *logosButton = [[UIButton alloc] init];
[logosButton setBackgroundImage:[UIImage imageNamed:#"logo_bar_alone.png"] forState:UIControlStateNormal];
[logosButton setBackgroundImage:[UIImage imageNamed:#"logo_bar_alone.png"] forState:UIControlStateHighlighted];
[logosButton addTarget:self action:#selector(logosButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[logosButton setFrame: CGRectMake(0, 0, width, logosHeight)];
[tempView addSubview: logosButton];
[[self view] addSubview: tempView];
[tempView release];
[[self view] addSubview: self.navBar];
self.navItem = [[UINavigationItem alloc] initWithTitle: #"Home"];
[self.navBar pushNavigationItem:self.navItem animated:NO];
}
The method: logosButtonClicked does get fired every now and then when I click on the UIButton, but I clearly am clicking on certain spots where nothing happens at all...
Very frustrating, I dont seem, to see a pattern in regards to where its active, but could someone please help out here?
EDIT
I think I have just stumbled across something, I changed the button to a UIButtonTypeRoundedRect and got rid of the images (and also made it larger) and it appears that I cannot click on the bottom OR top sections of the button where the button is rounded. So the middle rectangular section is the only section where I can click... why would this be?
EDIT 2
For anyone reviewing this question, please see taber's latest edit on his answer. The Navigation Controller is eating touches for some reason, and I need to figure out why this is so, could be a bug?
FINAL ANSWER :)
Okay after reviewing the project it looks like the UINavigationController that is positioned below the button is eating touches globally. Which is definitely weird because it was added as a subview BELOW your button. So there must be some kind of funky frame/touch-eating going on with the UINavigationController. I tried to set navigationController.titleView.userInteractionEnabled = NO but to no avail. If anyone knows how to basically make UINavigationController and UINavigationBar not eat touches (I'm talking about the background where no buttons exist) then please chime in. The UIButton touches work just fine when the UINavigationController isn't added to the view.
Original Answer
It may be some other UI elements in [self view] or tempView sitting on top of the button and intercepting taps. You might want to try either commenting out everything else in the view(s) and/or try setting the userInteractionEnabled property on them like this:
[otherUIElement setUserInteractionEnabled: NO];
EDIT:
This code makes it so that you CAN click the round rect edges but NOT the title text. So I suspect that it's some sort of subview preventing the button from catching the tap.
[logosButton addTarget:self action:#selector(logosButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[logosButton setFrame: CGRectMake(0, 0, 320.0, 50.0)];
[logosButton setTitle: #"HELLO" forState: UIControlStateNormal];
[logosButton.titleLabel setUserInteractionEnabled: YES];
EDIT #2:
Try using this subclassed button and see if the issue still occurs:
// NavBtn.h
#interface NavBtn : UIButton {
}
-(id)initWithTitle:(NSString *)text;
#end
// NavBtn.m
#import "NavBtn.h"
#implementation NavBtn
- (id)initWithTitle:(NSString *)text {
if ((self = [super initWithFrame: CGRectMake(0, 0, 320, 50)])) {
[self setTitle: text forState: UIControlStateNormal];
self.backgroundColor = [UIColor clearColor];
self.opaque = NO;
[self setBackgroundImage:[UIImage imageNamed:#"logo_bar_alone.png"] forState: UIControlStateNormal];
[self setBackgroundImage:[UIImage imageNamed:#"logo_bar_alone.png"] forState: UIControlStateHighlighted];
}
return self;
}
// i guess you shouldn't need to mess with layoutSubviews
#end
To load it into your view:
#import "NavBtn.h"
... in viewDidLoad, etc ...
NavBtn *btn = [[NavBtn alloc] initWithTitle: #"hey"];
[self.view addSubview: btn];
[btn release];
If THAT doesn't work, there's got to be some kind of third party library doing some funky category overriding of your UIButton class or something.

to display one view in another view by clicking button

hi guys i am new to iphone apps development please help me to show another view from one view using buttons
Thats a very vague question... here is a start - you can look up some of the syntax and research a bit:
this in viewDidLoad:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:#"Click" forState:UIControlStateNormal];
[button addTarget:self action:#selector(showView) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[button release];
then this method
- (void)showView {
UIView *view = [[UIView alloc] initWithFrame:CGRect(0,0,320,460)];
[self.view addSubview:view];
[view release];
}
if you want to push a view controller then you need to look up navigation controllers and the method pushViewController:animated:
This is the common code u can use to go on next view or go on back, Just change button name which u want to press and the view name on which u want to go. For example on back button press u want to go on library view then write this code -
-(IBAction)backButtonPressed:(id) sender
{
libraryView *libraryview=[[libraryView alloc] initWithNibName:nil bundle:nil];
libraryview.modalTransitionStyle=UIModalTransitionStyleCoverVertical;
[self presentModalViewController:libraryview animated:YES];
[libraryview release];
}
Let me know whether ur problem is solved or not.