removeFromSuperview doesn't work properly - objective-c

In class
#interface StartScene : UIView
I call an instance of
#interface HelpView : UIView {
GameOverMenu* gorm;
PlayScene* tView;
}
and use addSubview. I also got huge code here
-(void) removemyself {
[tView removeFromSuperview];
[gorm removeFromSuperview];
[self removeFromSuperview];
}
-(void)restartPlay {
[tView removeFromSuperview];
[self playSceneDidLoad];
}
-(void)gameOverDidLoad {
[tView removeFromSuperview];
gorm = [[GameOverMenu alloc]initWithFrame:CGRectMake(0, 0, 320, 520)];
gorm.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"backGround.jpg"]];
[gorm checkScore:Scores];
[self addSubview:gorm];
}
-(void)playSceneDidLoad {
[gorm removeFromSuperview];
tView = [[PlayScene alloc]initWithFrame:CGRectMake(0, 0, 320, 520)];
tView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"backGround.jpg"]];
[self addSubview:tView];
[tView ooneFingerTwoTaps];
}
And two sub classes of HelpView:
#interface PlayScene : HelpView
#interface GameOverMenu : HelpView <UITextFieldDelegate>
In StartScene when I push on a button, an instance of HelpView is created and in init method playSceneDidLoad is called.
Inside the PlayScene there is restart button which calls restartPlay method. When game is lost gameOverDidLoad method is called.
And In both PlayScene and GameOverMenu there are quit button, which calls removemyself method, that are supposed to return player to the main menu.
At first glance it should work fine, but if I press restart button for several times and than try to press Quit, it occurs that the views were not removed from superview, one press on a quit button only now removes them one by one.
And we stop on the HelpView, it didn't remove itself (even if I try to call [super removeFromSuperview]; somewhere.
I need to remove views correctly in time and to get to the main menu (StartScene) when quit is pressed. I don't think that a lot of views covering each other is a good variant. What is the problem?

Well I occurs that the point is that if super class' method is called from the subclass and there is such a command [self removeFromSuperview]; or [(someOtherSubview) removeFromSuperview];, it is subclass that uses self or (someOtherSubview). If our subclass doesn't have the pointed subView, than the command would do nothing. And if there is [self removeFromSubview];, subclass would remove itself.
Actually I solved this problem by using buttons as subView of superclass.

Related

How can I hide/remove a subview by default when it's superview loaded but still have access to it?

I have a view which displays a UILabel and UITextField subviews as well as an UIImageView and 2 UIButtons. These all make up a form. One of the fields is dedicated to date entry in dd/mm//yyyy format.
I decided to create another view (called datePickerView) inside my main view which holds a UIDatePicker instance. When the date field on the form mentioned above is clicked this view with the datepicker is show. Upon clicking the done button the view is hidden/removed again.
I have methods that deal with the showing and hiding of this view:
#property (weak, nonatomic) IBOutlet UIView *datePickerView;
- (void) hidePickerView {
[UIView animateWithDuration:0.5
animations:^{
[[self datePickerView] setFrame:CGRectMake(0, -250, 320, 50)];
} completion:^(BOOL finished) {
[[self datePickerView] removeFromSuperview];
}];
}
- (void) showPickerView {
[[self view] addSubview:[self datePickerView]];
[[self datePickerView] setFrame: CGRectMake(0, -250, 320, 50)];
[UIView animateWithDuration:1.0
animations:^{
[[self datePickerView] setFrame: CGRectMake(0, 152, 320, 260)];
}];
}
I call these methods in my textFieldDidEndEditing and textFieldShouldBeginEditing UITextField delegate methods.
My problem is the the view with the datepicker is visible when it's superview is first loaded. I tried dragging this datepicker view to the top of the hierarchy above all the textfields and buttons but this only shifts the view behind them.
I've also tried hiding the view through storyboard interface, tried adding a hide method to viewDidLoad, viewWillAppear. The methods I tested were:
[self datePickerView] removeFromSuperview];
[[self datePickerView] setHidden:YES];
[self hidePickerView];
These hide the datePickerView no problem but when I click the textfield the datePickerView doesn't show.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
// missing since date field error checking
if (textField == [self missingSinceField]) {
[self showPickerView];
return NO;
}
return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
if (textField == [self missingSinceField]) {
[self hidePickerView];
}
}
When I don't hide or remove the datePickerView in any way shape or form and tap it the datePickerView is loaded no problem.
** Just before posting this question I set a breakpoint in my showDatePicker method and when I uncomment [self datePickerView] removeFromSuperview]; I see that my datePickerView outlet is nil so this may explain why I'm having the issue I'm having. Commenting it again and trying again shows it as not being nil.
I think this is what's wrong but not sure how to make sure when viewDidLoad is run that my datePickerView isn't nil. I can't have it showing in the background of the form under the text fields and I don't think changing the colour of it to white so users can't see it isn't elegant.
Help would be appreciated.
Kind regards
I guess your IBOutlet property for datePickerView is weak, so, when you remove it from the superview it gets destroyed.
Either make it strong, or use the hidden property instead (remembering to set hidden to NO in showPickerView and YES in hidePickerView - where you currently add and remove the view).
You probably want to use the hidden property of the UIView subclass you are working with.
Source:
UIView reference
As far as your outlet being nil - make sure you have connected the IBOutlet to an actual element in the storyboard.

Using a UICollectionView over an SKScene

I have an app with several SKScenes. To keep it snappy, I have a single UIViewController, that handles 1 SKView.
I'm trying to add a UICollectionView to one of the SKScenes. However the problem comes when I try to set the delegate for the collection view to the SKScene initialising it.
I initialise it here:
- (id)initWithSize:(CGSize)size
{
if (self = [super initWithSize:size]) {
//Initialise collectionView
UICollectionViewLayout *layout = [[UICollectionViewLayout alloc] init];
_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height) collectionViewLayout:layout];
_collectionView.delegate = self;
_collectionView.dataSource = self;
[_collectionView setBackgroundColor:[UIColor redColor]];
}
return self;
}
After initialising, I add the collection view as a subview of the UIViewController's view by calling:
- (void)didMoveToView:(SKView *)view
{
[self.view addSubview:_collectionView];
}
But the delegate or datasource methods aren't called. I've set up the header:
#interface BrowseScene : SKScene <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
I'm guessing that despite setting self as the delegate, once the collection view is added, it is added as a subview of the UIViewController's SKView, and therefore has no reference to the SKScene that initialised it. I tried calling:
_collectionView.delegate = self.view.scene;
But I get a compiler error saying SKScene is an incompatible type for UICollectionViewDelegate.
So my question is, how best to approach this?
It turns out, the problem lay in how I was initialising the UICollectionView, not where. And it's perfectly ok to set an SKScene as the delegate class.
The main reason the delegates weren't being called was because I'd initialised the collectionView with an empty layout object (as UICollectionViewLayout is just an abstract class). I initialised with a standard UICollectionViewFlowLayout instead, and the methods were then called when the class initialised.
I was also missing a call to
[_collectionView registerClass:[collectionViewCell class] forCellWithReuseIdentifier:#"collectionViewCell"];
(In the complete code, I had calls to reloadData, so that wasn't the problem here).

Removing View from its superview getting a bad access error XCODE

since the release of the storyboard it has been a long time since I've used addSubview and removeFromSuperview. Obviously I have forgotten how to use them.
So on my UIViewControllerA I have this code for a button:
- (IBAction)buttonClickHandler:(id)sender {
dyf_FacebookViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:#"Facebook"];
[self.view addSubview:controller.view];
}
Which loads a UIView that is handled by UIViewControllerB. now this view can be called by many different ViewControllers to be a subview, which is why I have it remove itself from the superview.
So on UIViewControllerB I have this code:
- (IBAction)close:(id)sender {
[self.view removeFromSuperview];
}
Unfortunately that returns with a bad access error. Please help!
Thanks
Michael
EDIT:
The subview added (subview's viewcontroller) will be in control for removing itself as it is in control of the button on the subview. So I do not have access to the original controller.view variable as that is in ViewControllerA
You'll have to keep a reference to your dyf_FacebookViewController object, so you can do the following:
- (IBAction)close:(id)sender {
[controller.view removeFromSuperview];
}
What you're doing now is to remove your main view from its superview, which can have serious consequences, giving you a bad access.
if ([controller.view superView]) {
[controller.view removeFromSuperview];
}
Try this
- (IBAction)close:(id)sender {
for (UIView *subView in self.view.subviews) {
[subView removeFromSuperview];
}
}
If you want to remove the view you added, then keep a copy of the view controller...
// in this VC.m
#interface
#property (nonatomic, strong) dyf_FacebookViewController *dyfController;
#end
- (IBAction)buttonClickHandler:(id)sender {
self.dyfController = [self.storyboard instantiateViewControllerWithIdentifier:#"Facebook"];
[self.view addSubview:self.dyfController.view];
}
Later, to close the view...
[self.dyfController.view removeFromSuperview];

Passing data to a UIView - failure

I have a strange problem that I've never encountered before,
I have data in my viewController that I want to display in a UIView.
It's an iPad App which involve a SplitView Controller, when I click on an element within the table view (masterView) it execute a function in my detailViewController (via a protocol).
A function is executed which launch a UIView and send data to it:
myController:
- (void)SelectionChanged:(DocumentInfo*)document_info withDocu:(Document *)document{
DocumentView *viewDoc=[[DocumentView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
viewDoc.doc=document;
viewDoc.doc_info=document_info;
[viewDoc setBackgroundColor:[UIColor whiteColor]];
[self.view addSubview:viewDoc];
}
DocumentView.h
#import <UIKit/UIKit.h>
#import "Document.h"
#import "DocumentInfo.h"
#class Document;
#class DocumentInfo;
#interface DocumentView : UIView
#property(strong,nonatomic) Document *doc;
#property(strong,nonatomic) DocumentInfo *doc_info;
#end
DocumentView.m
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UILabel *titreDoc=[[UILabel alloc] initWithFrame:CGRectMake(20, 32, 339, 21)];
titreDoc.textColor = [self makeColorRGB_RED:66 GREEN:101 BLUE:149];
titreDoc.font = [UIFont fontWithName:#"System" size:(24.0)];
[self addSubview:titreDoc];
NSLog(#"%# - %#",doc,doc_info);
titreDoc.text=#"Nouveau Document";
}
return self;
}
My view is well displayed (I mean the label appear) but impossible to get the data which would have been passed to it... (the NSLog print (null) (null) )
Anybody know the reason why?
The problem seems pretty straight forward. You initialize your view (which means that you run - (id)initWithFrame:(CGRect)frame) and after that you're setting the data, so it's normal that you see null values into your init method because the ivars have not being set yet. What you could do is to modify your init method in order to construct your view taking into account these ivars. Something like this perhaps:
- (id)initWithFrame:(CGRect)frame doc:(Document *)doc docInfo:(DocumentInfo *)docInfo;
ps. If you choose to make your custom init method do not forget to call the designated initializer (-initWithFrame:) before any customization.
The reason the NSLog prints null is because the doc and doc_info are nil when the initWithFrame method is called. The doc and doc_info properties are set after the initWithFrame method is called in selectionChanged: method. Add the NSLog function after line 3 in selectionChanged method like this:
- (void)SelectionChanged:(DocumentInfo*)document_info withDocu:(Document *)document{
DocumentView *viewDoc=[[DocumentView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
viewDoc.doc=document;
viewDoc.doc_info=document_info;
NSLog(#"%# - %#",doc,doc_info);
[viewDoc setBackgroundColor:[UIColor whiteColor]];
[self.view addSubview:viewDoc];
}

calling addSubview in initWithNibName: causes viewDidLoad (and other UI Object inits)to fire before the addSubview Call executes

I'm adding a button in the middle of my initWithNibName:bundle:, when i add the button view to self.view, the view goes to start to initialize before it add's the button. So the Code in viewDidLoad gets fires before the initWithNibName:bundle: is finished. There is code below the addSubview that is relied on in the viewDidLoad and causes it to crash/not work since the init code has not run.
I've had the same experience when I added the button code to the viewDidLoad method. There is a UITableView in the .xib and the table gets inited before the rest of the viewDidLoad gets run and caused the tableView to get bad Data.
What is the best practice for adding a view to a view when you are initing and loading the view? just put all the addSubViews before the Return?
Thanks!
Here is my initWithNibName:bundle:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nil];
[self setIoUIDebug:(IoUIDebugSelectorNames)];
if (IoUIDebug & IoUIDebugSelectorNames) {
NSLog(#"%# - %#", [self description], NSStringFromSelector(_cmd) );
}
CGRect frame = CGRectMake(20, 521, 500, 37);
saveButton = [UIButton newButtonWithTitle:NSLocalizedStringFromTable(#"Save Animation Label",#"ScreenEditor",#"Save Animation Label")
target:self
selector:#selector(saveButtonPressedAction:)
frame:frame
image:[UIImage imageNamed:#"BlueButtonSmall.png"]
imagePressed:[UIImage imageNamed:#"BlueButtonSmallPressed.png"]
darkTextColor:NO];
[self.view addSubview:saveButton]; // <- Right here I'll hit breakpoints in other parts of viewDidLoad and cellForRowAtIndexPath, before the lined below get executed.
[saveButton setEnabled: NO];
[saveButton setUserInteractionEnabled: NO];
newAnimation = nil;
selectedSysCDAnimation = nil;
selectedIoCDTag = nil;
animationSaved = NO;
return self;
}
You should add the subviews inside viewDidLoad this will mean that the views are added when the main view is loaded into memory. I would reserve your initWithNibName:bundle: call for custom initialization and not interacting with the UI as this what viewDidLoad is designed for.
In regards to your tableView, you should put a call to load the tables datasource inside of viewDidLoad. Once the datasource is loaded, you can simply call reloadData on the tableview to load the data into the tableview.
For Example:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view addSubview:saveButton];
[self loadDataSource];
}
- (void)loadDataSource {
// load datasource here
[self.tableView reloadData];
}
Any access to the view property of the view controller will lazily initialize the view. This will trigger a call to viewDidLoad which will execute before the access to the view property returns in initWithNibName:. You should add the sub view in viewDidLoad or using interface builder.