Rigid Constraints vs. `-intrinsicContentSize` - ios

So I recently was creating what Apple calls a leaf-level view (a button) and so I followed Apple's docs to implement -intrinsicContentSize and everything worked (albeit the code felt a bit weird - I had constraints set up in my -updateConstraints method to position subviews, as well as code in the -intrinsicContentSize method to calculate what the total size should be; it felt like I was giving duplicate information to the autolayout system).
However, I also ran into a post on here claiming to, instead of using -intrinsicContentSize, use rigid constraints and then the containerview will automatically resize to fit the views it contains. I also implemented this, and achieved the same result as above, but this time I didn't feel like I was duplicating information sent (I just sent the straight constraints). Note that I see the view as described in the post mentioned above as a so called leaf-level view since it doesn't sound like any other view would be added to it.
Which implementation of resizing a container view based on the content inside of it is the proper way to go?
I'm currently leaning towards the second method, due to the fact that I don't think I should be sending duplicate information, however Apple's documentation says otherwise (then again, Apple's docs can be a bit confusing/misleading at times).
Sidenote about my specific situation, f it matters: I have two subviews in my button, one being an image, the other being a label. The image gets it's size from the label, and then the entire button from the image (so indirectly the sizing comes entirely from the label).

Your button view should have internal constraints, based on the label and the image. These should be sufficient to give it the correct size. You don't need to implement intrinsicContentSize for that.
The button's superview does not and should not know or care what is going on inside the button. You don't directly reference the intrinsic content size, the layout system does, and if your button has the right internal constraints, it isn't necessary.
Intrinsic content size is there to allow a view to express its size as something at the very bottom of the view hierarchy, based on its display contents, such as the text in a label. Everything above that is based on constraints.
You can also use it to allow a view with non-autolayout subviews to participate in autolayout, but this can lead to a lot of duplicated frame calculation code.

Related

Best approach to showing or hiding dynamic content in iOS

I've been doing iOS for a while now, but when it comes to dynamically hiding / showing elements, I'm a bit lost.
Coming from Android, I'm used to being able to simply set views to visibility gone, but this doesn't exist on iOS.
So let's say I have the following scenario:
Basically I want to have a table, but the table should not fill the entire view controller. Instead it should leave place for optionally either a button, a multiline label, or possibly both at the bottom (if visible, these should be fixed, not scroll).
One way to solve this would be to use auto layout and modify constraints, like adding a zero height constraint. But that would make iOS kill one of the other constraints, which would make it hard to change it again. For the label, I wouldn't always want to have a height constraint, because it could be multiline, and should take the size it needs.
Maybe it's easier to skip autolayout here and modify frames instead, I don't know.
My question is: What approach would be best here?
Is there some other way of doing this I haven't thought of, or do I have to try to do what I described above?
I'm not primarily looking for code (code can be ok), but I'm more interested in a description of how it can be done.
I'd like to support iOS 7.
This problem had a variety of solutions, and opinion based, but I'm facing such questions a lot, when I don't know what to choose and what would be the "right thing".
So, I my opinion, the best solution here is using autolayout, you need to set height of label manually, but you have a few methods for this, at least you can play with it and if you don't succeed ask question about it. Using frames, you'll face same problem of calculating height, right? But with auto layout, you only need to set height, vertical space to 0, when you need to hide message.
You can also use constrains with priority lower 1000, and remove completely constraints from message (button, label) if you don't need it at all anymore.
For example, taking your layout image, you can make UIView with subviews: button, label. Top constraint connect to the UITableView, other constraints to the sides.Label and button will calculate the view's height. The only question here is label height.
So in ios assuming that the background of both these objects is opaque only the front most view in the Heirarchy will be visible and interactable, An easy solution would be to change the different frames of these two things you need and make sure they are in the back of your view heirachy, and when you need them to appear use view.bringSubviewToFront(mySubview) and view.pushSubviewToBack(mySubview) to make it disappear again. View obviously would be referring to main view of your view controller.

What are the advantages of using Auto Layout with views created programmatically?

Auto Layout Constraints allow me to size and lay out views perfectly, without knowing beforehand what screen they will be rendered on. This works reasonably well when I'm drawing a UI on a Storyboard.
Let's move on to creating views programmatically.
My app is running, the interface has been rendered on the screen, I have all the necessary coordinates and the sizing has been done.
I would like to create a few views dynamically, for instance:
a UIImageView, that appears at the press of a button, gets animated, then disappears
a collection of custom UIView, created and laid out on the screen depending on the underlying data model (imagine a sequence of events here, arranged on a custom timeline)
In similar scenarios, I still tend to use the good old frames, e.g.:
let myView = UIView(frame: CGRectMake(x, y, w, h))
without adding any NSLayoutConstraint.
Is there any definite advantage of using constraints instead, given the added complexity, especially when you need to animate views?
The most important aspects are when you actually calculate your frame (which method), if you want universal support and if you need to support various orientations.
Inside a viewController, if you print out your self.view frame in viewDidLoad and viewWillAppear: or viewWillLayoutSubviews, it might have different values. The final frame (for example, the one for iPhone 6 plus) is not calculated in viewDidLoad. So if you make your view setup there, the calculation will be wrong.
But with constraints, it does not matter where you add them. You might need to call layoutIfNeeded after the view changes, but you don't need to worry weather the frames have their final value.
For views that are visible only for a short time, auto layout could make a difference for different orientations. By using frames, you will have to update the frame of your temporary view in the orientation change callback.
Also, if you use auto layout in the storyboard, using static frames for views created programmatically might not give you the results you are expecting. But, of course, it depends on the particularities of your project.

Problems with autolayout and resizable views

I have issue with autolayout.
I have three different views (could be n views as well). When I pin first one to top of super view and connect one next to the other everything seems fine. But if I want to change height of first one the other two does not follow (they stay on the same position). What I find weird about this is that if I connect only two views this works perfectly.
To have better understanding what I am trying to achieve I made simple, example solution with three views:
http://i.stack.imgur.com/cMwiB.png
So, when I set height of green view to 0 ( can be any other number as well ) and only red view is connected, this works fine, red will move as it should. Blue one is not connected and it remains where it is:
Here is screenshot when I connect blue to red:
What I tried to do:
connect blue one to green as well ( not working)
connect blue only to green ( not working )
"boxing": have boxes with views at the time ( ugly, hard to manage, not working in all cases)
What I would like to know:
what makes this happen? Can I change this kind of behavior?
What is the best practice to have flexible length for height (Besides UITableView)
Thanks in advance.
Ok, I think you're falling into the same trap I did, when I investigated autolayout some time ago. It's tricky to explain, but I'll do my best. When you work with autolayouts, you need to forget completely about setting a view's frame at all. And that, my friend, includes changing size and positioning. When you use autolayout, you define some constraints, some "rules", that the view tries to respect when rendering the screen, so the more specific the rules are, the less random will be the behavior of the view. I mean, if you just define the spacing between views, you're implying that the height of the views doesn't matter, so it's possible that some views grow or shrink when the re-layout is called (that is, if you don't specify a constraint for size. You probably want to always specify the size of some views in every layout...)
By the way, you're allowed to violate the constraints by manually changing the frame of an element AFTER a re-layout is called, but when the re-layout method is called again, the constraints will be forced so the size and positioning of the views will change. Quick tip: an easy way to force the re-layout method is to change orientation (command+left / command+right in the simulator).
So after saying that, I have to say that the layout you provided is completely working as intended, at least to me. When you change orientations the constraints you specified are ALWAYS being respected. If you want, you can try to apply some frame-setting in the viewDidAppear method, because this one is called AFTER the autolayout (and thus, you're able to violate the constraints temporally). After doing this, your view will be broken but once you change orientation the constraints should be respected again. Make sure it's that way.
From here I can only wish you luck ;) Oh, and refer to the documentation, it was a life saver to me when I looked at this half a year ago. https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/Introduction/Introduction.html It might seem a classic, but it's a pretty nice doc.
EDIT: one last thing. I have the impression that constraints are not designed to be dynamic. You define them once, and they're there always. Their main purpose is to ensure that subviews are rendered as intended in every screen resolution without fail, so if I were to make an application with moving views, I would leave them outside of the autolayout, or avoid using it at all. Just a personal impression though :)

Is there an easy way to reposition views in iOS without manually changing origin/size/center?

I find myself often having to reposition subviews of a view after hiding or showing one of them. The way I'm doing this is by programmatically changing a view frame's origin and/or size, or its center. But is there an easier way I'm missing? Is there a way to do it with Autosizing masks?
I don't think there's any automatic way of doing this. You could probably get clever about how you do it programmatically (e.g. if you used a set of sequential tag identifiers, you could loop through and calculate the height of the previously visible tag to calculate the origin of the next subview; or if there are a group of subviews that are always going to move together, you could put them in a container UIView and thus move a whole bunch of them by just moving their container view; etc. ... it depends upon how they're laid out and which fields might be hidden).
This won't help you for now, but check out WWDC 2012 session 202 for a discussion of a relevant improvement in iOS 6.

Why is the UIPageViewController resizing its UIViewControllers views after the page turn?

Within the pageViewController:viewControllerAfterViewController: method, just before the return statement, the view which is about to be returned as the next page has the correct view frame size.
However immediately after the pageViewController:didFinishAnimating:previousViewControllers:transitionCompleted: method is called, I check the frame size of the newly introduced view controller ([pageViewController2.viewControllers objectAtIndex:0];) and I find it resized.
Note that, I have set [self.pageViewController.view setAutoresizesSubviews:NO] and the autoresizing mask to None for the newly created ViewController.
Any ideas in which step the new ViewController is being resized?
I think the problem is inherently related to the nature of UIPageViewController. It is built from UIScrollView. I don't exactly know why there is strange resizing behavior, but it seems to be particularly pronounced when the view controllers that make up your pages use auto layout. Seemingly, locking the constraints in your page view controllers to the superview makes the elements resize after the transition because the superview is itself getting resized after said transition.
This sucks because Apple is basically pushing all of us to adopt auto layout. Auto layout is awesome, and I recommend everyone use it from now on, but it really really sucks when you use it with a UIPageViewController. They really ought to either scrap that class or build something easier for developers, something that can be dragged into a storyboard outright.
A few things to consider.
1.) Don't lock anything to the "Top Layout Guide" or the "Bottom Layout Guide". Also make sure you have "Constrain To Margins" disabled on any view intended to hug the sides of the screen.
2.) If you are using a label in your individual page / content view controllers, make sure you bind/constrain it to something other than the superview. I wanted to place a label over a UIImageView, so I aligned the label to the leading and top edges of the image view (using AutoLayout constraints only), creating an offset to give the label some margins.
3.) The following would otherwise be a good tutorial. However, it is a bit outdated. I downloaded the project and basically modified it to get a UIPageViewController implementation that works. The only problem with this project is that it doesn't use AutoLayout. I'm currently writing a blog post that more clearly discusses how to use UIPageViewController and Autolayout together.
http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/

Resources