ViewController added programmatically looks shifted/transalted (iOS, swift, storyboards) - ios

I'm learning about View Controller Containers and nesting Viev Controllers in iOS, using swift and storyboard.
The problem is - added view is not within the bounds of a parent view.
This is how it looks in interface builder:
The left view is parent view controller, and the white area is view, in which I want to place blue view controller.
I imagine, that the blue view controller should fill this white view.
However, this is how it looks on iPad:
It looks, like the blue view is placed the same amount pixels below the top of white view, as is the white view to the top of the screen.
Here's the code:
class ViewController: UIViewController {
#IBOutlet weak var vcContainer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
var vc = self.storyboard?.instantiateViewControllerWithIdentifier("TestViewController")
displayVC(vc!)
}
func displayVC(content: UIViewController) {
content.view.frame = self.vcContainer.frame
content.view.setNeedsLayout()
self.vcContainer.addSubview(content.view)
self.addChildViewController(content)
content.didMoveToParentViewController(self)
}
}
Any help would be appreciated. Thanks!

This line: self.vcContainer.addSubview(content.view)
it should be self.view.addSubview(content.view)
Because when you set frame for your child viewcontroller like this:
content.view.frame = self.vcContainer.frame
it is relative to parent viewcontroller, not vcContainer, hence after you added content into vcContainer, it's in wrong position.
If you want to add content into vcContainer, you should choose another way to place content.view, something like pin edges of content to edges of vcContainer using NSLayoutConstraint.
Full working code:
UIViewController *vc =
[self.storyboard instantiateViewControllerWithIdentifier:#"vc"];
[self addChildViewController:vc];
vc.view.translatesAutoresizingMaskIntoConstraints = NO;
[self.container addSubview:vc.view];
[self.container addConstraint:[NSLayoutConstraint
constraintWithItem:vc.view
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.container
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0]];
[self.container addConstraint:[NSLayoutConstraint
constraintWithItem:vc.view
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.container
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0]];
[self.container
addConstraint:[NSLayoutConstraint
constraintWithItem:vc.view
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self.container
attribute:NSLayoutAttributeLeading
multiplier:1.0
constant:0]];
[self.container
addConstraint:[NSLayoutConstraint
constraintWithItem:vc.view
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:self.container
attribute:NSLayoutAttributeTrailing
multiplier:1.0
constant:0]];
[vc didMoveToParentViewController:self];
Adding constraints will be a lot easier if you use PureLayout.

The constraints set in your StoryBoard on your view specify an exact distance to be kept from the top.
This distance is true for some devices, so it might looks like it is in the middle, but on the ipad this is not the case.
You should add a height on your view, and than position vertically and horizontally to the center of your superview.

Related

How to add subview with half-transparent background which won't break and won't be affected by AutoLayout?

I want to show user that application is loading data using some progress bar and label on top of view which will be shown after the data is loaded. This view is not initial, so I cannot use LaunchScreen for these purposes. What's the best way to do so?
The view which will be shown after uses AutoLayout, and it'd better be that view on top uses AutoLayout as well, but those AutoLayouts shouldn't interact with each other in any way.
First create a custom UIView class, and customize the view according to your requirement. i.e. transparent background, add image/label etc. using autolayout/with the help of code.
Now add this custom view (yourSubView) into its containerview and add some constraint so that it place in right location.
The following code will add a subview after keep space 80px in all side (left, right, top, bottom), you can add constraint according to your requirement.
[yourContainerView addSubview:yourSubView];
yourSubView.translatesAutoresizingMaskIntoConstraints =
NO;
[yourContainerView addConstraint:[NSLayoutConstraint constraintWithItem:yourSubView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:yourContainerView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:80.0]];
[yourContainerView addConstraint:[NSLayoutConstraint constraintWithItem:yourSubView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:yourContainerView attribute:NSLayoutAttributeRight multiplier:1.0 constant:80.0]];
[yourContainerView addConstraint:[NSLayoutConstraint constraintWithItem:yourSubView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:yourContainerView attribute:NSLayoutAttributeTop multiplier:1.0 constant:80.0]];
[yourContainerView addConstraint:[NSLayoutConstraint constraintWithItem:yourSubView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:yourContainerView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:80.0]];
What about using something like https://github.com/sgryschuk/SGNavigationProgress?

Embed a UIView in another UIView with cascading Autolayout

My goal:
I'm trying to find a general recipe how to add views that I created in Interface Builder to a parent view that I create in Interface Builder as well, while letting their layout constraints determine the size of their respective parent views.
The key idea is to get cascading views with a variable size. A view should first determine its own size by resolving its layout constraints. Once it's done it has a fixed size from its superview's perspective so now the superview can determine its size by resolving its own layout constraints and so on.
My approach:
I create a new XIB file in Xcode and open it in Interface Builder. Next, I drag another UIView from the Object library to the XIB's view in order to add it as a subview. Using layout constraints I pin all four sides of the subview to its superview's edges:
Now I create another XIB file which is supposed to be the subview. I drag a UILabel and a UIButton to its view. I give the button a fixed height constraint and add more constraints to pin the label and the button to the view's edges:
Now comes the tricky part that I haven't been able to solve yet:
I couldn't find any way to add the view of this second XIB file to the subView of the first XIB using only Interface Builder (is this even possible?) so I tried it by writing some code. I created a UIView custom class and set the class value in Interface Builder accordingly. In the custom class I added this method:
- (void)awakeFromNib {
UIView *view = [[[NSBundle mainBundle] loadNibNamed:#"DynamicSubView" owner:self options:nil] objectAtIndex:0];
[self.subView addSubview:view];
view.translatesAutoresizingMaskIntoConstraints = NO;
[self addConstraintsForView:view];
}
- (void)addConstraintsForView:(UIView *)view {
[self addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.subView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.subView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.subView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.subView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
}
The method addLayoutConstraintsForView: adds constraints to the view from the second XIB that pins all its four edges to the subView's edges. Now the subView should resize dynamically with the view it contains. However, it doesn't seem to work. Any idea or a good recipe how to deal with this?
Remark: The top most view here is intended to be a UITableViewCell. I want it to layout itself and pass its height to its tableView using the method introduced here.

Auto layout of a Child Container that embeds a UIViewController

My main scene shows a child UIViewController, by putting a Child Container in its View, and embedding a child UIViewController in that Child Container. I do that by ctrl-dragging from the Child Container to the child UIViewController in the storyboard, and choosing the "embed" segue.
That lets me encapsulate and reuse the child UIViewController elsewhere. I think that is fairly standard. But I can't get it to auto layout properly.
I've made a simple test case to demonstrate this:
https://github.com/murraycu/ios-example-autolayout-of-child-container-views
It has two UIViewControllers that are embedded in a Tab Controller so you can switch between them.
The "Simple" tab shows the SimpleViewController, which shows an image and a label, seen here in the storyboard:
Neither the UIImage or the UILabel has a height constraint specified, though they have an Equal Width (equal to the parent view) constraint to keep the widths simple.
That UILabel is clearly not very high but the UIImage and UILabel have slightly different Content Hugging priorities, making their heights not ambiguous according to Auto Layout. So thanks to auto layout, when I set its text at runtime to some text that would require more space, it takes up more space, taking space away from the UIImage above it. That's good - it is the behaviour that I want, as seen in the emulator:
Now to the problem: The "With Child Container" tab shows the WithChildContainerViewController, which shows the same image but shows my ChildViewController (embedded in a Child Container) instead of the UILabel. And that embedded ChildViewController shows the UILabel. Here it is in the storyboard:
However, the auto layout system now doesn't seem to know how much space the Child Container needs to show all the text in the label in my ChildViewController. As in the "Simple" tab, neither the UIImage or the Child Container has a height constraint specified. Now XCode complains that "Height is ambiguous for "container view". And it looks like this in the simulator:
That's improved if I add a constraint to the Child Container, constraining its bottom to the bottom of the parent view, as suggested by #iphonic: https://github.com/murraycu/ios-example-autolayout-of-child-container-views/commit/1d295fe0a6c4502764f8725d3b99adf8dab6b9ae but the height is still wrong:
How can I let the auto layout system know what to do? I've thought about implementing UIView's intrinsicContentSize, but UIViewController isn't a UIView.
Suggestion is, do it programatically rather than via IB. See below
_childController=[self.storyboard instantiateViewControllerWithIdentifier:#"ChildController"];
[self addChildViewController:_childController];
[_container addSubview:_childController.view];
[_childController didMoveToParentViewController:self];
_childController.view.frame=_container.bounds;
//add constraints
UIView *subView=_childController.view;
UIView *parent=_container;
subView.translatesAutoresizingMaskIntoConstraints=NO;
NSLayoutConstraint *width =[NSLayoutConstraint
constraintWithItem:subView
attribute:NSLayoutAttributeWidth
relatedBy:0
toItem:parent
attribute:NSLayoutAttributeWidth
multiplier:1.0
constant:0];
NSLayoutConstraint *height =[NSLayoutConstraint
constraintWithItem:subView
attribute:NSLayoutAttributeHeight
relatedBy:0
toItem:parent
attribute:NSLayoutAttributeHeight
multiplier:1.0
constant:0];
NSLayoutConstraint *top = [NSLayoutConstraint
constraintWithItem:subView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:parent
attribute:NSLayoutAttributeTop
multiplier:1.0f
constant:0.f];
NSLayoutConstraint *leading = [NSLayoutConstraint
constraintWithItem:subView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:parent
attribute:NSLayoutAttributeLeading
multiplier:1.0f
constant:0.f];
[parent addConstraint:width];
[parent addConstraint:height];
[parent addConstraint:top];
[parent addConstraint:leading];
Hope it helps.
Cheers.
#iphonic's code but using Visual Format Language
_childController = [self.storyboard instantiateViewControllerWithIdentifier: #"ChildController"];
[self addChildViewController: _childController];
[_container addSubview: _childController.view];
[_childController didMoveToParentViewController: self];
//add constraints
NSDictionary *views = #{#"subView": _childController.view,
#"parent": _container};
[parent addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat: #"V:|[subView(==parent)]"
options: 0
metrics: nil
views: views]];
[parent addConstraints: [NSLayoutConstraint
constraintsWithVisualFormat:#"H:|[subView(==parent)]"
options: 0
metrics: nil
views: views]];

iOS: Autolayout differences with appliying constraints to subview on iOS 7 and iOS 8

I have a view controller set up in a storyboard. The view controller's view contains a subview(UITableView) with pinned edges to the 4 sides of its parent, essentially making the view fill its parent.
I am adding the view controller's main view as a subview of another view controller's view like this:
UIView *overlayView = firstViewController.view;
[overlayView setTranslatesAutoresizingMaskIntoConstraints:NO];
UIView *sourceView = secondViewController.view;
[sourceView addSubview:overlayView];
NSLayoutConstraint *constraint;
constraint = [NSLayoutConstraint constraintWithItem:overlayView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:sourceView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0];
[sourceView addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:sourceView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:overlayView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:100];
[sourceView addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:overlayView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:sourceView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
[sourceView addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:overlayView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:sourceView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
[sourceView addConstraint:constraint];
[sourceView layoutIfNeeded];
I want to have a gap from the right edge of the view to its parent equal to 100 pixels.
Now weirdly enough this works as expected on iOS 8, but fails to do so on iOS 7 and the view is displayed full-screen ignoring the 100 constant set on the trailing constraint. Also, if the view controller's view that is being added has no child views - then it is working as expected. Is setTranslatesAutoresizingMaskIntoConstraints: being applied to all the subviews of a view in iOS 7 ? What might be the reason for this ?
EDIT:
The issue lies somewhere in the way subviews are being managed by the OS.
When the Container View is set as a outlet to the view property of the view controller, things don't work. If however, I set the Table View as an outlet to the view property, the it works. Something weird happens if there is a child view with pinned edges to its superview and then I am adding other constraints to the superview. I dont understand why it works fine on iOS 8 though...
EDIT 2
The problem seems to happen only with the trailing constraint. If I want to modify the constants of any of the other constraints there are no issues ?!
Can you try interchanging sourceView with overlayView in your constraint?
`constraint = [NSLayoutConstraint constraintWithItem:sourceView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:overlayView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:100];`
This essentially means that sourceView.trailing - 100 = overlayView.trailing; which is not what you would want.
Edit 1:
Is setTranslatesAutoresizingMaskIntoConstraints: being applied to all the subviews of a view in iOS 7?
NO. translatesAutoresizingMaskIntoConstraints is set only for the views you explicitly call setTranslatesAutoresizingMaskIntoConstraints for.

Center UIView on screen using Auto Layout programmatically when the view is located at the top of the view hierarchy

I have implemented a popup UIView which I add to the topmost window via [[[[UIApplication sharedApplication] windows] lastObject] addSubview:popupView], so it will appear on top of everything even the keyboard. I need to ensure this popup view that I programmatically created will always remain centered on screen. I was attempting to add auto layout constraints, but it doesn't like the fact I'm trying to align with the topmost window. Could you let me know how I could accomplish this? Thank you.
This is what I have implemented, which will generate a (nicely detailed) error that states 'The view hierarchy is not prepared for the constraint ... the constraint's items must be descendants of that view':
[popupView setTranslatesAutoresizingMaskIntoConstraints:NO];
NSLayoutConstraint *cn = nil;
cn = [NSLayoutConstraint constraintWithItem:popupView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:[[[UIApplication sharedApplication] windows] lastObject]
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0];
[popupView addConstraint:cn];
cn = [NSLayoutConstraint constraintWithItem:popupView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:[[[UIApplication sharedApplication] windows] lastObject]
attribute:NSLayoutAttributeCenterY
multiplier:1.0
constant:0];
[popupView addConstraint:cn];
cn = [NSLayoutConstraint constraintWithItem:popupView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1
constant:blockSize.height];
[popupView addConstraint:cn];
cn = [NSLayoutConstraint constraintWithItem:popupView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1
constant:blockSize.width];
[popupView addConstraint: cn];
Don't go sticking your view into a window that wasn't set up specifically to hold your views. You don't know what the real owner of that window might do, now or in a future version of iOS.
Create your own window and set its windowLevel high enough to be above the keyboard. Give the new window its own root view controller (so it will handle different orientations properly) and center your popup view inside that root view controller's view.
You will find lots of useful information in the answers to this question.
It's fine to add the height and width constraints to popupView, but since popupView is a subview of the window, the centering constraints should be added to the window, not the popupView (and you need to add the popupView as a subview first, before you add the constraints).

Resources