Change UIView of storyboard dynamically and keep the rest of the subviews in place - cocoa-touch

I have a storyboard and I am trying to change the UIView to set a custom gradient view that I have created.
I have tried self.view = myNewViewWithGradient; and the gradient is displayed, but no other element can be seen since I am replacing the current view.
How can I set a new view dynamically and keep the elements that have been added in the storyboard?
I have tried re-adding the subviews (that have a referencing outlet) to this new view, but nothing is displayed.
[self.view addSubview:self.txtPassword];
Thanks for your help.
UPDATE: here is a screenshot of the outlets set in the storyboard:

You can add all your subviews to your new view, something like:
[myNewViewWithGradient setFrame:self.view.frame];
for (UIView* v in [self.view subviews]) {
[myNewViewWithGradient addSubview:v];
}
self.view = myNewViewWithGradient;
but I can not see what are you trying to achieve, did you just want a new background? You can do somehting like:
[self.view addSubview:myNewViewWithGradient];
[self.view sendSubviewToBack:myNewViewWithGradient];
Your sendSubviewToBack:myNewViewWithGradient is an UIView? If it did not work please provide more information so we can better help you :)

Related

UIScrollView doesn't update properly, shows empty view randomly

I am trying to open a new view on select of a table cell in a previous view. The new view that I am trying to open, consists of different sub-views or modules. Hence, I populate each sub-view one by one inside in [self populate] method which is in triggered inside the viewDidLoad method.
-(void)viewDidLoad{
[super viewDidLoad];
[self populate];
}
-(void) populate{
[self.edgeGallery loadImagesWithURLs: _items];
// Modular view: main info
[self.vwListingMainView setListing: _listing];
[self.vwListingMainView refresh];
// Modular view: listing agents
_vwListingAgentsView.agentsArray = _listing.agents;
// Modular view: listing info
_vwListingInfoView.listing = _listing;
[_vwListingInfoView refresh];
// Modular view: Listing activities
_vwListingActivityView.listing = _listing;
[_vwListingActivityView requestCounts];
}
Every time a new subview is populated, the method viewWillLayoutSubViews is called. This is the method where I compute the subview's height and other constraints and append it to the superview.
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
[self computeAndFixHeight];
}
- (void) computeAndFixHeight {
// Adjusting each module's height
_cstMainInfoHeight.constant = [_vwListingMainView getViewHeight];
_cstListingActionsHeight.constant = [_vwListingActionsView getViewHeight];
_cstListingAgentsHeight.constant = [_vwListingAgentsView getViewHeight];
_cstListingInfoViewHeight.constant = [_vwListingInfoView getViewHeight];
// Adjusting scroll view height
NSInteger computedScrollHeight = _vwListingUpcomingEventView.frame.origin.y + [_vwListingUpcomingEventView getViewHeight];
[self.scrollView setContentSize:CGSizeMake(self.view.frame.size.width, computedScrollHeight)];
_cstContainerBottom.constant = -computedScrollHeight - kDefaultNegativeScrollH;
[self.view layoutIfNeeded];
[self.view updateConstraints];
}
However, once the view is loaded completely, the problem that I am facing is that sometimes, I get the complete view and sometimes, randomly, I get an empty view. I think [self.view layoutIfNeeded] is the problem, but I have also tried using [self.view setNeedsLayout] and [self.view setNeedsUpdateConstraints], but still the problem remains. Any help would be appreciated.
Please excuse me if I am doing anything stupid. I am new to iOS development.
I created this project just for your question to show how to update a scrollView just using AutoLayout (no need to override viewWillLayoutSubviews, update the scrollView's contentSize, call layoutIfNeeded or updateConstraints)
Hope it helps you =)
https://github.com/ghashi/ScrollViewQuestion/tree/master
This is the result:
In our project we had encountered similar issue where we had to add a lot of views to a content view of a scrollview using constraints added programatically. Writing constraints for each view not only made the view controller bloated, it was also static. To add another view we had to write the constraints again.
We end up creating subclass of UIView that now managed this for us. We named this NNVerticalStackView.h,.m.

Subviews added to documentView of NSScrollView not showing up

I have a NSView wrapped in a NSScrollView using the IB. In the initialization function of the view (class is NoteView) containing the NSScrollView, I attempt to add subviews to the NSView as follows:
// Initialize custom view with width 802 and height 130, call it initialSubview
// Set initialSubview's frame origin to (20.0, 580.0). documentView of scrollView
// is size (842.0, 740.0)
// Let innerView be the documentView of the scrollView (I have an IBOutlet attaching
// the scrollView's document view to innerView)
[innerView addSubview:initialSubview];
When I do this, nothing shows up. Likewise, trying this:
[[[scrollView] documentView] addSubview:initialSubview];
doesn't work either. However, if I added it to the contentView:
[[[scrollView] contentView] addSubview:initialSubview];
The subview shows up fine. Any ideas?
As an addendum, if I add something like an NSButton to the documentView in the IB, nothing
shows up as well.
I figured out the issue. It seems NSScrollView and Auto-layout fight themselves.
The solution is to remove whatever you're documentView is (in my case innerView)
from their superview, setTranslatesAutoresizingMaskToConstraints to no, and re-add the view.
The code looks something like this:
[innerView removeFromSuperView];
[innerView setTranslatesAutoresizingMaskIntoConstraints:NO];
[scrollView setDocumentView:innerView];
Then you have to set any constraints you'd like manually
I am pretty sure contentView is the correct place to add it. You may also need to update the content size.
Adding views to a NSScrollView from IB adds the view to the NSScrollView's contentView(NSClipView).
According to your setup you have
NoteView is clip view(contentView) of the NSScrollView.
document view of the scroll view is innerview.
inner view(documentView)'s subview which is initialSubView is added from
-initWithFrame: of contentView.
In an NSScrollView a contentView represents the 'clipped' representation of the documentView.
Having the documentView initialized in init of the contentView is why nothing happens.
Do This
Add NoteView from -awakeFromNib or similar entry point as documentView of the NSScrollView.
Add initialSubView as a subview of NoteView.

Adding NSView to window not on top?

I am adding a subview programmatically and adding it to the main windows context view to cover up the entire context view like so:
loadingView = [[LoadingView alloc] initWithFrame:[mainWindow.contentView frame]];
NSLog(#"%#", [mainWindow.contentView subviews]);
[mainWindow.contentView addSubview:loadingView];
NSLog(#"%#", [mainWindow.contentView subviews]);
[mainWindow makeFirstResponder:loadingView];
The NSLog's confirm that loadingView is being added last in the contentView subviews. I have also tried:
loadingView = [[LoadingView alloc] initWithFrame:[mainWindow.contentView frame]];
[mainWindow.contentView addSubview:loadingView positioned:NSWindowAbove relativeTo:nil];
[mainWindow makeFirstResponder:loadingView];
That didn't work either. For some reason the two tableviews (created in IB) at the bottom of the window are on top of the new view I've added. Here's a snapshot of the window, note that the red part is what should be on top with the progress bar and a few labels:
It's also worth noting that the view has it's alpha set to 0.9 which is why you can somewhat see behind it.
GW
If you place one view above another, the objects in the previous view will be visible in above view. What you need do is remove previous views from window and then add a new subview.
Try using:
//Create IBOutlet of your tableview in your .h file
IBOutlet NSTableView* yourTableView;
// Add this line where you are adding your subview to remove the tableview from superview.
[yourTableView removeFromSuperview];
// Then add your loading view as the subview
loadingView = [[LoadingView alloc] initWithFrame:[mainWindow.contentView frame]];
[mainWindow.contentView addSubview:loadingView];
Then whenever your want your tableView back use:
[window contentView]addSubview: yourTableView];
As long as you use nil here, you will not get predictable results.
[mainWindow.contentView addSubview:loadingView positioned:NSWindowAbove relativeTo:nil];
If you have not already done so, put all the other views inside a containing view.
Make the containing view the only view that is a direct child of the window content view.
Now add your subview with the above method and replace nil with a reference to the containing view.
In OS X, overlapping siblings have certain nuances when it comes to drawing. In your case, the loadingView and the two table views are siblings because they are all added as subviews of the window's content view and they overlap hence the nuances are coming into play.
From Apple's Documentation
For performance reasons, Cocoa does not enforce clipping among sibling
views or guarantee correct invalidation and drawing behavior when
sibling views overlap. If you want a view to be drawn in front of
another view, you should make the front view a subview (or descendant)
of the rear view.
I don't have the definitive solution for this but reading these should help improve your understanding for the long term.
http://www.cocoabuilder.com/archive/cocoa/327817-overlapping-sibling-views.html
Is there a proper way to handle overlapping NSView siblings?

UIButton inside UIView doesn't respond to touch events

I've put a UIButton inside a custom UIView and the button is not receiving any touch events (it doesn't get into the highlighted state, so my problem is not about being unable to wire up a touch inside up handler). I've tried both putting it into the XIB in Interface Builder, and also tried programatically adding the UIButton into the UIView seperately, both ended with no luck. All my views are inside a UIScrollView, so I first though UIScrollView may be blocking them, so I've also added a button programatically exactly the same way I add my custom view into UIScrollView, and the button worked, elimination the possibility of UIScrollView could be the cause. My View's hiearchy is like this:
The button is over the image view, and the front layer isn't occupying my button completely, so there's no reason for me not be physically interacting with the button. At my custom view's code side, I'm creating my view as such:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
UIView *sub = [[[NSBundle mainBundle] loadNibNamed:#"ProfileView" owner:self options:nil] objectAtIndex:0];
[self addSubview:sub];
[sub setUserInteractionEnabled:YES];
[self setUserInteractionEnabled:YES];
CALayer *layer = sub.layer;
layer.masksToBounds = YES;
layer.borderWidth = 5.0;
layer.borderColor = [UIColor whiteColor].CGColor;
layer.cornerRadius = 30.0;
/*layer.shadowOffset = CGSizeZero;
layer.shadowRadius = 20.0;
layer.shadowColor = [[UIColor blackColor] CGColor];
layer.shadowOpacity = 0.8;
*/
}
return self;
}
I've tried all combinations of setUserInteractionsEnabled, and had no luck. (Yes, also set them to checked in Interface Builder too). I've also read in another question with a similar problem that I should try overriding 'canBecomeFirstResponder' to return 'YES' and I've also done that too. But the problem persists, I can't click the button. I've not given any special properties, settings to the button, it's just a regular one. My other objects in the view (labels below, image view behind the button etc.) are working properly without problems. What could be possibly wrong here?
Thanks,
Can.
UPDATE: Here is a quick reproduction of the problem: https://dl.dropbox.com/u/79632924/Test.zip
Try to run and click the button.
Looking at the test project, I believe your problem in the way you create TestView, you do not specify the frame for it, so basically the parent view is 0 size, and the subviews you see from XIB extending out of the parent view and thus do not get anything in responder chain.
You should either specify the frame when creating TestView, or adjust the frame after loading XIB file.
I have had this problem as well. The cause for me was that the UIButton superview frame was of height 0, so I believe that even though a touch was happening, it was not being passed down to the button.
After making sure that the button's superview took a larger rectangle as a frame the button actions worked.
The root cause for this problem on my side was a faulty auto layout implementation (I forgot to set the height constraint for the button's superview).
I've found the solution. I was initializing my custom view as:
MyView *view = [[MyView alloc] init];
I've initialized it instead with a frame of my view's size, and it started responding to events:
CGRect rect = CGRectMake(0,0,width,height);
MyView *view = [[MyView alloc] initWithFrame:rect];
Storyboard Solution
Just for anyone wanting a solution to this when using storyboards and constraints.
Add a constraint between the superview (containing the button) and the UIButton with an equal heights constraint.
In my case, I had selected embed UIButton in a UIView with no inset on the storyboard. Adding the additional height constraint between the UIButton and the superview allowed the UIButton to respond to touches.
You can confirm the issue by starting the View Debugger and visually confirm that the superview of the UIButton is not selectable.
(Xcode 11, *- Should also work in earlier versions)

Add lots of views to NSScrollView

I'm trying to add one subview (view from an NSViewController) for every element in a dictionary to a NSScrollView to get kind of a tableview, but with much more flexibility over the cells.
Is it possible to place (programmatically) e.g. 100 subviews underneath each other so that you have to scroll down the NSScrollView to get to the last element?
The short answer is yes. I have done this before, and I assure you that it will work. Let me also assure you that it is not quite as simple as it looks ;)
The way to do this is to maintain one content view, in which you add all of your custom rows as subviews programmatically. Note that you will either have to resize the contentView before adding all of the rows, or you will have to turn off autoresizing for the row views. Set the documentView of your scrollView to this custom contentView, and you should be good to go.
Yes, simply initialize the views programmatically using (i.e.)
NSView *subView = [[NSView alloc] initWithFrame:CGRectMake(10,10,100,100)];
then add to the main using addSubview: method of the main view.
Remember to manually release the subview when you've done with it (that means, when you have added it to the main view).
As example you can do something like
int height x = 10, y = 10, width = 100, height = 100;
for(int i = 0;i<100;i++) {
NSView *subView = [[NSView alloc] initWithFrame:CGRectMake(x,y + height*i,width,height)];
[scrollView addSubview:subView];
[subView release];
}