Removing a programatically created view iOS - ios

in my game app i created a view programatically with a uibutton.
by clicking the button the whole view shall be removed. but i had no success with all my attempts to remove the view with "[polygonView removeFromSuperview];" for example.
I think i need to
get the current view first but have no idea how to do that and to implement that in the
button method.
here is the code:
- (void) addNewView {
UIWindow *window = [UIApplication sharedApplication].keyWindow;
UIView *polygonView = [[UIView alloc] initWithFrame: CGRectMake ( 60, 0, 900, 900)];
polygonView.backgroundColor = [UIColor blueColor];
polygonView.tag = 42;
// [self playMovie];
[window addSubview:polygonView];
// [polygonView setHidden:NO];
[polygonView release];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(100, 170, 100, 30);
[button setTitle:#"Click Me!" forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
[polygonView addSubview:button];
// NSLog(#"mike=%# tag=%d",[[polygonView class] description], [polygonView tag]);
}
-(void)buttonPressed {
NSLog(#"Button Pressed!");
[polygonView removeFromSuperview];
}

You need to get a hold of your polygonView:
-(void)buttonPressed {
UIView *polygonView = [[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];
[polygonView removeFromSubview];
}

Related

Switching between views in Objective C

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// UIScreen represents the entire screen. Its bounds method
// returns the rectangle that corresponds to the entire screen
// CGRect is a C struct that used to group four floating
// point values that represent the x and y coordinates of the upper left
// corner, as well as the width and the height.
//
CGRect windowRect = [[UIScreen mainScreen] nativeBounds];
UIWindow *window = [[UIWindow alloc] initWithFrame:windowRect];
[window setBackgroundColor:[UIColor lightGrayColor]];
[self setWindow:window];
UIViewController *vc = [[UIViewController alloc]init];
window.rootViewController = vc;
self.mainView = vc.view;
[window makeKeyAndVisible];
//Window is now visible
//Add created views to the mainView to make them visible.
//Example : add a "Hello World" label
UIView *dealerView=[[UIView alloc]initWithFrame:self.mainView.bounds];
UIView *view1=[[UIView alloc]initWithFrame:self.mainView.bounds];
CGRect labelRect = { 150.0, 150.0, 150.0, 50.0 };
UIButton *button1 = [[UIButton alloc] initWithFrame:labelRect];
[button1 setBackgroundColor:[UIColor blackColor]];
[button1 setTitle:#"ENTER HERE" forState: (UIControlState)UIControlStateNormal];
[button1 addTarget:self action:#selector(enterHereClicked:)
forControlEvents:UIControlEventTouchUpInside];
[button1 setUserInteractionEnabled:YES];
[view1 addSubview:button1];
[dealerView addSubview:view1];
return YES;
}
-(void) enterHereClicked:(UIButton *) button{
CGRect labelRect = { 150.0, 400.0, 150.0, 50.0 };
UIButton *sender=button;
UIView *view1=[sender superview];
UIView *view2=[[sender superview]superview];
[view1 removeFromSuperview];
UIView *view=[[UIView alloc]initWithFrame:self.mainView.bounds];
UIButton *button2 = [[UIButton alloc] initWithFrame:labelRect];
[button2 setBackgroundColor:[UIColor blackColor]];
[button2 setTitle:#"Another View" forState: (UIControlState)UIControlStateNormal];
[button2 addTarget:self action:#selector(clickView:) forControlEvents:
UIControlEventTouchUpInside];
[view addSubview:button2];
[view2 addSubview: view];
}
-(void)clickView:(UIButton *) button{
NSLog(#"anand");
UIButton *sender=button;
UIView *view1=[sender superview];
UIView *view3=[[sender superview]superview];
[view1 removeFromSuperview];
CGRect labelRect = { 150.0, 400.0, 150.0, 50.0 };
UIView *view=[[UIView alloc]initWithFrame:labelRect];
[view setBackgroundColor:[UIColor greenColor]];
[view3 addSubview:view];
}
I have edited the code as per you advise. But still not working.
I am creating a new view dealerview and adding and removing the subviews views from it. I am going somewhere wrong but still could not figure it out.
Looks like I am going wrong in the -(BOOL) application method.
It's very atypical to do this sort of thing in the app delegate. It would be better to do this in a subclass of UIViewController and add an instance of that subclass as the rootViewController of the UINavigationController you make key and visible in didFinishLaunchingWithOptions.
You also likely do not want to remove the root view of a UIViewController from it's super view. Currently, you care creating an action for a button that removes its superview, vc.view, from the view hierarchy. The problem is view1 and self.mainView are the same so with:
UIView *view1=[sender superview];
[view1 removeFromSuperview];
[self.mainView addSubview:view];
You're removing a view from the view hierarchy then adding a view to the view that's just been removed and expecting to see it.
You should have one view that acts as a container for button1 and another view that acts as a container for button2 but are both added and removed to/from self.mainView.
UIButton *addVehicleBackbtn=button;
UIView *addVehicleView=[addVehicleBackbtn superview];
[addVehicleView setHidden:YES];
I did hide the View using setHidden:YES in order to switch back between the views.

Remove a subview from UIViewController

I'm adding a subview to the main view but then I cant remove it from this view.
NextViewController *nextView = [[NextViewController alloc] init];
nextView.transitioningDelegate = self;
nextView.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self.presentedViewController.view addSubview:nextView.view];
nextView.view.frame = CGRectMake(724, 80, 300, 150);
UIButton *stayButton = [[UIButton alloc] initWithFrame:CGRectMake(101, 94, 90, 49)];
[stayButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[stayButton setTitle:#"Detener" forState:UIControlStateNormal];
[stayButton addTarget:self
action:#selector(waitForNextView)
forControlEvents:UIControlEventTouchUpInside];
[nextView.view addSubview:stayButton];
stayButton.titleLabel.font = [UIFont systemFontOfSize:25];
[stayButton setTitleColor:[UIColor colorWithRed:(255/255.0) green:(255/255.0) blue:(255/255.0) alpha:1] forState:UIControlStateNormal];
here I'm adding a button to the view and then when the button is pushed it goes`-
(void)waitForNextView{
transition = NO;
NextViewController *nextView = [[NextViewController alloc] init];
SectionViewController *sectionView = [[SectionViewController alloc]init];
[self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
actualSection = 0;
[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(dismissView2) userInfo:nil repeats:NO];
}
I've tried with:
[nextView.view removeFromSuperView];
[nextView.presentedViewController removeFromParentViewController];
But I don't know what else can I do :S
If you want more information, nextView is a UIViewController of 300x100 size. I want to present it and then remove it when I hit the button, that's all.
I would be great if someone can help me.
Thanks
You are creating different reference and then you're trying to remove it from its superview while not being added at all. I will try to explain:
1. When you're adding nextView.view to self.view you have created a instance like this
NextViewController *nextView = [[NextViewController alloc] init];
2. When you're trying to remove it, instead of referring to the instance above you're creating a brand new one again in your waitForNextView method like so again
NextViewController *nextView = [[NextViewController alloc] init];
and then you're trying to remove it. Please note that the last instance of nextView has not being added anywhere yet, and this is the reason your code doesn't work.
In order to work you should refer to the first reference you've added to self.view. Please adjust your code as shown below
In your ViewController.m
#interface ViewController()
{
NextViewController *nextView;
}
When adding your viewController
nextView = [[NextViewController alloc] init];
nextView.transitioningDelegate = self;
nextView.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self.presentedViewController.view addSubview:nextView.view];
nextView.view.frame = CGRectMake(724, 80, 300, 150);
UIButton *stayButton = [[UIButton alloc] initWithFrame:CGRectMake(101, 94, 90, 49)];
[stayButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[stayButton setTitle:#"Detener" forState:UIControlStateNormal];
[stayButton addTarget:self
action:#selector(waitForNextView)
forControlEvents:UIControlEventTouchUpInside];
[nextView.view addSubview:stayButton];
stayButton.titleLabel.font = [UIFont systemFontOfSize:25];
[stayButton setTitleColor:[UIColor colorWithRed:(255/255.0) green:(255/255.0) blue:(255/255.0) alpha:1] forState:UIControlStateNormal];
And finally in your IBAction method
-(void)waitForNextView{
transition = NO;
[self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
actualSection = 0;
[nextView removeFromSuperview];
}
The problem here is that you are adding the button as a subview to the view of nextView, so removing the view of nextView won't work.
If you add a tag to your button, then you can retrieve the subview by using the tag. Eg. When you define your button:
[stayButton setTag:1];
Then in the waitForNextView method, you can get the control like this:
UIButton *stayButton = (UIButton*)[nextView.view viewWithTag:1];
[stayButton removeFromSuperView];
use this code in the methode dismissView2
for (UIView *subview in view.subviews ){
[subview removeFromSuperview];
}

executing an action in a different view controller

In my application, I am trying to create a button, with a button. My code right now is as follows:
- (IBAction)doneTextField:(id)sender {
YourShortcutsViewController *YSVC2 = [self.storyboard instantiateViewControllerWithIdentifier:#"ViewController2"];
YSVC2.stringFromTextField = self.textField.text;
[self presentViewController:YSVC2 animated:YES completion:nil];
{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(0, 0, 100, 50);
[btn addTarget:self action:#selector(newButtonClicked) forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:#"FaceTime" forState:UIControlStateNormal];
[self.view addSubview:btn];
}
}
this works, but I need the button that is being added to add in a different view controller, not the view controller that the code is in.
How would I do this??
Thank you
You need to create a function to add the button in the new view controller:
In YourShortcutsViewController.h:
-(void)addFaceTimeButton:(UIButton*);
In YourShortcutsViewController.m:
-(void)addFaceTimeButton:(UIButton*){
[self.view addSubview:btn];
}
And then change your code to:
- (IBAction)doneTextField:(id)sender {
YourShortcutsViewController *YSVC2 = [self.storyboard instantiateViewControllerWithIdentifier:#"ViewController2"];
YSVC2.stringFromTextField = self.textField.text;
[self presentViewController:YSVC2 animated:YES completion:nil];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(0, 0, 100, 50);
[btn addTarget:self action:#selector(newButtonClicked) forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:#"FaceTime" forState:UIControlStateNormal];
[YSVC2 addFaceTimeButton:btn];
}

How to dismiss a subView generated by code?

In my project I want to show a first run view when starting the app for te first time. To do this I added a UIView to my mainViewCntroller.m. To dismiss this (overlayed) view I put a button on the view called acceptButton. What code do I have to add to the Button to remove this view from the stack?
What do I do wrong?
Here's my code:
- (void) firstRun {
if (((AppDelegate*)[UIApplication sharedApplication].delegate).firstRun)
{
CGFloat height = [[UIScreen mainScreen] bounds].size.height;
CGFloat width = [[UIScreen mainScreen] bounds].size.width;
NSLog(#"%f", height);
CGRect myFrame = CGRectMake(0, 0, width, height);
UIView *myView = [[UIView alloc] initWithFrame:myFrame];
myView.backgroundColor = [UIColor scrollViewTexturedBackgroundColor];
myView.tag = 12345;
[self.view addSubview:myView];
// Create a ScrollView and a label
UIScrollView *discScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(20.0f, 0.0f, self.view.frame.size.width - 20, self.view.frame.size.height -70)];
discScroll.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
UILabel *discLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,0,0)];
discLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
NSString *labelText = NSLocalizedString (#"InfoText",#"");
[discLabel setText:labelText];
// Tell the label to use an unlimited number of lines
[discLabel setNumberOfLines:0];
[discLabel setNumberOfLines:0];
[discLabel setBackgroundColor:[UIColor clearColor]];
[discLabel setFont:[UIFont boldSystemFontOfSize:17]];
discLabel.textColor = [UIColor colorWithRed:255 green:255 blue:255 alpha:1.0];
//[infoLabel sizeToFit];
CGSize infoLabelSize = [discLabel.text sizeWithFont:discLabel.font
constrainedToSize:CGSizeMake(discScroll.frame.size.width, 5000)
lineBreakMode:UILineBreakModeWordWrap];
discLabel.frame = CGRectMake(0, 0, infoLabelSize.width, infoLabelSize.height);
discScroll.contentSize = infoLabelSize;
[discScroll addSubview:discLabel];
[self.view addSubview:discScroll];
UIButton *acceptButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
acceptButton.frame = CGRectMake(110, [[UIScreen mainScreen] bounds].size.height - 74, 100, 44);
// position in the parent view and set the size of the button
[acceptButton setTitle:#"Click Me!" forState:UIControlStateNormal];
// add targets and actions
[acceptButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
// add to a view
[self.view addSubview:acceptButton];
}
}
-(IBAction)buttonClicked:(id)sender
{
[[self.myView viewWithTag:12345] removeFromSuperview];
}
In my mainViewController.h is the following property:
#property (weak, nonatomic) IBOutlet UIView *myView;
EDIT I've post the complete code. Maybe something else is in the way.
Ive written it in Xcode, following Code works for me.
Ive opened a new XCode Project (Single View based), and just added following Code:
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
myView.backgroundColor = [UIColor scrollViewTexturedBackgroundColor];
myView.tag = 12345;
[self.view addSubview:myView];
UIButton *acceptButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
acceptButton.frame = CGRectMake(0, 0, 100, 44);
[acceptButton setTitle:#"Click Me!" forState:UIControlStateNormal];
[acceptButton addTarget:self action:#selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
[myView addSubview:acceptButton];
[myView release];
}
- (void)buttonClicked{
[[self.view viewWithTag:12345] removeFromSuperview];
}
This worked for me in iPhone Simulator.... Just this code in the MainViewController.m nothing else... Just give it a try, hope it works for you too :-)
[acceptButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
when your method is called acceptButton, change to
[acceptButton addTarget:self action:#selector(acceptButton:) forControlEvents:UIControlEventTouchUpInside];
your target is set to buttonClicked but you are using acceptButton
[acceptButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
-(IBAction)buttonClicked:(id)sender
{
[self.myView removeFromSuperview];
}
The problem lies with the [acceptButton addTarget:self action:#selector(buttonClicked:) line. Change buttonClicked to your method acceptButton: in that call.
[acceptButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
The exception is clear, there is no function named "buttonClicked"
Just change the part of your code with below code;
[acceptButton addTarget:self action:#selector(acceptButton:) forControlEvents:UIControlEventTouchUpInside];
just give it a tag...
UIView *myView = [[UIView alloc] initWithFrame:myFrame];
myView.backgroundColor = [UIColor scrollViewTexturedBackgroundColor];
myView.tag = 12345;
[self.view addSubview:myView];
[myView release];
-(IBAction)acceptButton:(id)sender{
[[self.view viewWithTag:12345] removeFromSuperview];
}
Also change
action:#selector(buttonClicked:)
to
action:#selector(acceptButton:)

how to load same tableview with different NSArrays depending on uibuttons tapped?

In my app i have a scroll-view and a table-View added as a sub-view and on this scroll view i have multiple menu buttons (UI Button) added as sub-view to my scroll-view.i want to load the table-View with different arrays depending on respective menu button is tapped.Any Ideas?
- (void)viewDidLoad
{
[super viewDidLoad];
[self PutButtoninScrollView:7];
}
-(void)PutButtoninScrollView:(int)numberOfbuttons
{
myButton1=[[UIButton alloc]init];
myButton1= [UIButton buttonWithType:UIButtonTypeCustom];
myButton1.frame=CGRectMake(5, 5, 70, 30);
[myButton1 setTitle:#"दुनिया" forState:UIControlStateNormal];
[myButton1 setTag:1];
myButton1.backgroundColor=[UIColor blackColor];
[myButton1 addTarget:self action:#selector(ListViewAction:) forControlEvents:UIControlEventTouchUpInside];
[self.myScrollView addSubview:myButton1];
myButton2=[[UIButton alloc]init];
myButton2= [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton2.frame=CGRectMake(80, 5, 70, 30);
[myButton2 setTitle:#"India" forState:UIControlStateNormal];
[myButton2 addTarget:self action:#selector(ListViewAction:) forControlEvents:UIControlEventTouchUpInside];
[self.myScrollView addSubview:myButton2];
[self.myScrollView setContentSize:CGSizeMake(160, 35)];
_myScrollView.backgroundColor=[UIColor redColor];
[self.view addSubview:self.myScrollView];
}
-(void)ListViewAction:(id)sender
{
NSLog(#"sucessful");
if ([myButton.currentTitle isEqualToString:#"दुनिया"])
{
NSLog(#"successful again 1");
}
else if ([myButton.currentTitle isEqualToString:#"भारत"])
{
NSLog(#"successful again 2");
}
}
problem is when i execute the code
"successful" is displayed. that means ListViewAction method is getting called but my if statement is never executed.
try this
-(void)PutButtoninScrollView:(int)numberOfbuttons
{
xPosition=5;
for(int i=0;i<numberOfbuttons;i++)
{
myButton= [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame=CGRectMake(xPosition, 5, 70, 30);
myButton.backgroundColor=[UIColor redColor];
[myButton setTitle:[NSString stringWithFormat:#"%d",i] forState:UIControlStateNormal];
[myButton setTag:i];
[myButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.myScrollView addSubview:myButton];
xPosition+=75;
}
[self.myScrollView setContentSize:CGSizeMake(xPosition,35)];
_myScrollView.backgroundColor=[UIColor redColor];
[self.view addSubview:self.myScrollView];
}
- (void) buttonClicked:(id) sender
{
NSString *strTitle = [sender currentTitle];
// arrItem have list of array items
NextView *detailViewController = [[NextView alloc] initWithNibName:#"NextView" bundle:nil];
detailViewController.arrTableView =[arrItem objectAtIndex:[strTitle integerValue]];
[self.navigationController pushViewController:detailViewController animated:YES];
}
-(void)ListViewAction:(id)sender
{
NSLog(#"sucessful");
if ([[sender currentTitle] isEqualToString:#"दुनिया"])
{
NSLog(#"successful again 1");
}
else if ([[sender currentTitle] isEqualToString:#"भारत"])
{
NSLog(#"successful again 2");
}
}
try this
[myButton1 addTarget:self action:#selector(ListViewAction:) forControlEvents:UIControlEventTouchUpInside];
[myButton2 addTarget:self action:#selector(ListViewAction:) forControlEvents:UIControlEventTouchUpInside];

Resources