How do I find the most parent SuperView? - ios

I'm trying to add a new subView to a page, such that everything but itself is greyed out. However, I'm calling it from within a subview of the screen. To get it out, I have to do the following :
[self.view.superview.superview.superview.superview addSubview:self.cardDialog.view];
As you can surmise, this is extremely bad code. How can I find the proper parent level and set it correctly?

If the view is part of the view hierarchy, use the window property.
UIView* topView = self.view.window;
Or if your view is not on screen yet, you can get the window indirectly through your app delegate
UIView* topView = [UIApplication sharedApplication].delegate.window;
Else, if your target is not the window, you can walk up the view hierarchy until you find the view you want:
UIView* topView = self.view;
while(topView.superview != nil){
topview = topView.superview;
if( /*topview is the one you were looking for*/ ){
break;
}
}

I've found myself on this situation once and I gave up. I decided to use a modalView instead with a cross disolve transition. Not only you avoid the problem you are having but it helps keeping things organized.
Lately I improved this aproach by grabing a snapshot of the parentVC and sending it to the modalView, then I apply a tint. The overall effect is exactly what you are looking for, I guess.

Related

IOS: Open UIView at Vertical coordinate

Does anyone know of a way to load a view controller at a point other than the top. This would be similar to opening a web page part way down ie Go to Target
This is not a tableview or webview so the point is not to go to a specific row of the table or place in the webview. Rather it is a regular UIVIewController and the point is to go to a specific vertical point on the screen where there is some relevant content.
Thanks for any suggestions.
Edit: I ended up using the following, not as elegant as I was hoping, but adequate:
-(void) raiseView:(float) float {
CGRect contextRect = self.view.bounds;
float boundsY = contextRect.origin.y;
contextRect.origin.y=boundsY+float;
self.view.bounds = contextRect;
}
I recommend reading up further on controller based interface and how to best use the common practices to your advantage.
My suggestion would be to rely on the presentation styles available to aUIViewController. Here would be an example of presenting a view controller over the current view:
MyViewController *controller = [[MyViewController alloc] init];
controller.modalPresentationStyle = UIModalPresentationOverCurrentContext;
[currentViewController presentViewController:controller animated:YES completion:^{
// Do whatever you need to here
}];
Then upon completion, you can do anything you need to for presenting your content. Here you can simply set the controllers view to be whatever frame you desire (with, in your terms, any top point you would like). This way you can present a VC to the user and display anything you need on top at the point relevant to the content on the previous view.
Happy coding!

Force UINavigationBar to overlay container below instead of pushing it down

I was just wondering if there is a simple way to specify whether a UINavigationBar should overlay its content when shown. I currently have a UINavigationController that contains a custom UIViewController with a UIScrollView, which contains a UIPageViewController (I wanted a zooming/scrollable UIPageViewController).
When I call:
[self setNavigationBarHidden:NO animated:YES];
From within my UINavigationController, the UINavigationBar animates in, but pushes the custom container with all its content down, instead of overlaying it.
The bar is set to translucent and I've tried all the settings I can think of. I changed the extendEdges settings in the child view controllers and that resized the content when the navigation bar came in, instead of pushing it down. But I still can't work out how to get it to overlay instead.
Many thanks.
Ok, apologies. This just reveals how little I know about iOS programming...
I noticed that the container's view origin y value was -44. So adding the following within my container class:
- (void) viewDidLayoutSubviews
{
CGRect boundsRect = self.view.bounds;
boundsRect.origin = CGPointMake(0, 0);
self.view.bounds = boundsRect;
}
Results in the view staying at the top of the screen, so the UINavigationBar overlays it nicely when it appears.
EDIT: Actually the proper way appears to be just calling:
self.automaticallyAdjustsScrollViewInsets = NO;

topLayoutGuide in child view controller

I have a UIPageViewController with translucent status bar and navigation bar. Its topLayoutGuide is 64 pixels, as expected.
However, the child view controllers of the UIPageViewController report a topLayoutGuide of 0 pixels, even if they're shown under the status bar and navigation bar.
Is this the expected behavior? If so, what's the best way to position a view of a child view controller under the real topLayoutGuide?
(short of using parentViewController.topLayoutGuide, which I'd consider a hack)
While this answer might be correct, I still found myself having to travel the containment tree up to find the right parent view controller and get what you describe as the "real topLayoutGuide". This way I can manually implement automaticallyAdjustsScrollViewInsets.
This is how I'm doing it:
In my table view controller (a subclass of UIViewController actually), I have this:
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
_tableView.frame = self.view.bounds;
const UIEdgeInsets insets = (self.automaticallyAdjustsScrollViewInsets) ? UIEdgeInsetsMake(self.ms_navigationBarTopLayoutGuide.length,
0.0,
self.ms_navigationBarBottomLayoutGuide.length,
0.0) : UIEdgeInsetsZero;
_tableView.contentInset = _tableView.scrollIndicatorInsets = insets;
}
Notice the category methods in UIViewController, this is how I implemented them:
#implementation UIViewController (MSLayoutSupport)
- (id<UILayoutSupport>)ms_navigationBarTopLayoutGuide {
if (self.parentViewController &&
![self.parentViewController isKindOfClass:UINavigationController.class]) {
return self.parentViewController.ms_navigationBarTopLayoutGuide;
} else {
return self.topLayoutGuide;
}
}
- (id<UILayoutSupport>)ms_navigationBarBottomLayoutGuide {
if (self.parentViewController &&
![self.parentViewController isKindOfClass:UINavigationController.class]) {
return self.parentViewController.ms_navigationBarBottomLayoutGuide;
} else {
return self.bottomLayoutGuide;
}
}
#end
Hope this helps :)
I might be wrong, but in my opinion the behaviour is correct. The topLayout value can be used by the container view controller to layout its view's subviews.
The reference says:
To use a top layout guide without using constraints, obtain the guide’s position relative to the top bound of the containing view.
In the parent, relative to the containing view, the value will be 64.
In the child, relative to the containing view (the parent), the value will be 0.
In the container View Controller you could use the property this way:
- (void) viewWillLayoutSubviews {
CGRect viewBounds = self.view.bounds;
CGFloat topBarOffset = self.topLayoutGuide.length;
for (UIView *view in [self.view subviews]){
view.frame = CGRectMake(viewBounds.origin.x, viewBounds.origin.y+topBarOffset, viewBounds.size.width, viewBounds.size.height-topBarOffset);
}
}
The Child view controller does not need to know that there are a Navigation and a Status bar : its parent will have already laid out its subviews taking that into account.
If I create a new page based project, embed it in a navigation controller, and add this code to the parent view controllers it seems to be working fine:
you can add a constraint in the storyboard and change it in viewWillLayoutSubviews
something like this:
- (void)viewWillLayoutSubviews
{
[super viewWillLayoutSubviews];
self.topGuideConstraint.constant = [self.parentViewController.topLayoutGuide length];
}
The documentation says to use topLayoutGuide in viewDidLayoutSubviews if you are using a UIViewController subclass, or layoutSubviews if you are using a UIView subclass.
If you use it in those methods you should get an appropriate non-zero value.
Documentation link:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/topLayoutGuide
In case if you have UIPageViewController like OP does and you have for example collection view controllers as children. Turns out the fix for content inset is simple and it works on iOS 8:
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
UIEdgeInsets insets = self.collectionView.contentInset;
insets.top = self.parentViewController.topLayoutGuide.length;
self.collectionView.contentInset = insets;
self.collectionView.scrollIndicatorInsets = insets;
}
This has been addressed in iOS 8.
How to set topLayoutGuide position for child view controller
Essentially, the container view controller should constrain the child view controller's (top|bottom|left|right)LayoutGuide as it would any other view. (In iOS 7, it was already fully constrained at a required priority, so this didn't work.)
I think the guides are definitely meant to be set for nested child controllers. For example, suppose you have:
A 100x50 screen, with a 20 pixel status bar at the top.
A top-level view controller, covering the whole window. Its topLayoutGuide is 20.
A nested view controller inside the top view covering the bottom 95 pixels, eg. 5 pixels down from the top of the screen. This view should have a topLayoutGuide of 15, since its top 15 pixels are covered by the status bar.
That would make sense: it means that the nested view controller can set constraints to prevent unwanted overlap, just like a top-level one. It doesn't have to care that it's nested, or where on the screen its parent is displaying it, and the parent view controller doesn't need to know how the child wants to interact with the status bar.
That also seems to be what the documentation--or some of the documentation, at least--says:
The top layout guide indicates the distance, in points, between the top of a view controller’s view and the bottom of the bottommost bar that overlays the view
(https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILayoutSupport_Protocol/Reference/Reference.html)
That doesn't say anything about only working for top-level view controllers.
But, I don't know if this is what actually happens. I've definitely seen child view controllers with nonzero topLayoutGuides, but I'm still figuring out the quirks. (In my case the top guide should be zero, since the view isn't at the top of the screen, which is what I'm banging my head against at the moment...)
This is the approach for the known guide length. Create constrains not to guides, but to view's top with fixed constants assuming guide distance will be.
Swifty implementation of #NachoSoto answer:
extension UIViewController {
func navigationBarTopLayoutGuide() -> UILayoutSupport {
if let parentViewController = self.parentViewController {
if !parentViewController.isKindOfClass(UINavigationController) {
return parentViewController.navigationBarTopLayoutGuide()
}
}
return self.topLayoutGuide
}
func navigationBarBottomLayoutGuide() -> UILayoutSupport {
if let parentViewController = self.parentViewController {
if !parentViewController.isKindOfClass(UINavigationController) {
return parentViewController.navigationBarBottomLayoutGuide()
}
}
return self.bottomLayoutGuide
}
}
Not sure if anyone still got problem with this, as I still did a few minutes ago.
My problem is like this (source gif from https://knuspermagier.de/2014-fixing-uipageviewcontrollers-top-layout-guide-problems.html).
For short, my pageViewController has 3 child viewcontrollers. First viewcontroller is fine, but when I slide to the next one, the whole view is incorrectly offset to the top (~20 pixel, I guess), but will return to normal after my finger is off the screen.
I stayed up all night looking for solution for this but still no luck finding one.
Then suddenly I came up with this crazy idea:
[pageViewController setViewControllers:#[listViewControllers[1]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:^(BOOL finished) {
}];
[pageViewController setViewControllers:#[listViewControllers[0]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:^(BOOL finished) {
}];
My listViewControllers has 3 child viewcontrollers. The one at index 0 has problem, so I firstly set it as root of pageviewcontroller, and right after that set it back to the first view controller (as I expected).
Voila, it worked!
Hope it helps!
This is an unfortunate behavior that appears to have been rectified in iOS 11 with the safe-area API revamp. That said, you will always get the correct value off the root view controller. For example, if you want the upper safe area height pre-iOS 11:
Swift 4
let root = UIApplication.shared.keyWindow!.rootViewController!
let topLayoutGuideLength = root.topLayoutGuide.length

Add clickable and fixed subview to UITableViewController?

I'd like to place an ADBannerView object onto my UITableView screen statically, what means that I want it to always stay above my toolbar (self.navigationController.toolbar), even when the user is scrolling the tableview. I've solved this by adding by ADBannerView as a subview to my toolbar and given it negative values for the frames origin:
[self setBannerViewSize];
[self.navigationController.toolbar addSubview:bannerView];
The only problem is: I can't click and open the iAd this way - I can see the banner but nothing happens when I tap on it.
Since I'm also using a refreshControl, the option to use a UIViewController instead of UITableViewController and add a tableView manually wouldn't work for me. Is there any other way I can get my ADBannerView statically showing in my table view controller AND still being tappable?
Thank you in advice!
Yay!! After all I succeeded in solving this (really annoying) problem by myself (and a lot of reading around)!
First, I found this really world-changing post. Basically this post handles with the topic that a UITableViewController uses self.view for its tableView property, so overriding the tableView property (or synthesizing it manually) plus giving self.view a new view (from application) and adding tableView as its subview would make it possible to reach the real superview of tableView.
But this still didn't solve my problem, although I was sure it would, because it all made sense. My bannerView appeared in the right place (and was fixed) but it still didn't do anything when clicked. But there was a second minor thing I didn't know about:
As I read in this post the superview of a subview doesn't only have to be userInteractionEnabled but also have a non-transparent backgroundColor. Because my superviews background color was set to [UIColor clearColor] it all didn't work - but setting its backGroundColor to e.g. blackColor solved the whole problem: the bannerView got finally tappable! :)
So, my code is now looking like this:
#synthesize tableView;
- (void)viewDidLoad
{
[super viewDidLoad];
if (!tableView && [self.view isKindOfClass:[UITableView class]]) {
tableView = (UITableView *)self.view;
}
self.view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
self.tableView.frame = self.view.bounds;
[self.view addSubview:self.tableView];
[self resizeTableToFitBanner];
self.view.backgroundColor = [UIColor whiteColor];
[self.view addSubview:bannerView];
// some other code
}
BannerViewController in Apple's iAdSuite sample code solves this problem very elegantly:
https://developer.apple.com/library/ios/samplecode/iAdSuite/Introduction/Intro.html
I think you should use a container view, and set things up in IB. You can add a tool bar and ADBannerView to the bottom of the view of your navigation controller's root view controller. Fill the rest of the space with a container view - this will give you an embedded view controller automatically. You should delete this one and then drag in a tableViewController and control drag from the container view to the tableViewController to hook up the embed segue.

UISplitViewController Multiple Detail Views Segmented Control

I'm working on an iPad app in a split view controller where the app will remain in landscape the entire time. I would like the root view controller to remain a list and the detail view controller to swap out 4 different views controlled by a UISegmentedControl.
I'm following this post here UISegmentedControl Best Practice, however when I swap in my view controllers, they don't properly fit in the detailview controller, they are cut off as if they are trying to draw for ipad portrait orientation.
If I completely ignore the segmented control approach and have a detail view, the view size properly in the detail view, but once i try to swap them in with a segmented control is where I run into trouble.
Is there a way to tell the swapped in views to draw correctly?
Have you tried:
swappedInView.frame = detailController.view.bounds;
when you call
[detailedController.view addSubview:swappedInView];
?
Their contents need to have their resizing behaviors (most easily in xcode/IB) set appropriately.
I am using a UISegmentControl as well, but adding my views programmatically. I have my default view (segment 0) loaded first in the viewDidLoad of the rootController. Then based on which segment is pressed, I check if the view has been initialized, if not, initialize, then add it as a subview. Then remove the other view. I had a similar post on this on how to keep track of it that might help you out, and has the code from Beginning iPhone 4 Development book that I used for my own app. Here's the code snippet to get you started if you want to go this approach:
if (self.yellowViewController.view.superview == nil)
{
if (self.yellowViewController == nil)
{
YellowViewController *yellowController =
[[YellowViewController alloc] initWithNibName:#"YellowView"
bundle:nil];
self.yellowViewController = yellowController;
[yellowController release];
}
[blueViewController.view removeFromSuperview];
[self.view insertSubview:yellowViewController.view atIndex:0];
}
else
{
if (self.blueViewController == nil)
{
BlueViewController *blueController =
[[BlueViewController alloc] initWithNibName:#"BlueView"
bundle:nil];
self.blueViewController = blueController;
[blueController release];
}
[yellowViewController.view removeFromSuperview];
[self.view insertSubview:blueViewController.view atIndex:0];
}
In my own, I add as a subview, instead of inserting it behind the other views (they had a toolbar in the front in their example). So if say segment 3 was pressed, then I would check the other views if their superviews were present, remove that view, add my view. Hope that helps.

Resources