UIView with UILabel subview - responding to AutoLayout changes - ios

I've got a UIView with a UILabel subview that has constraints defined like so:
constraints = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-10-[_messageLabel]-50-|" options:0 metrics:nil views:views];
[self addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-0-[_messageLabel]-0-|" options:0 metrics:nil views:views];
[self addConstraints:constraints];
In certain instances, the label is not big enough to show all the text, so it is truncated.
When I adjust the size of the UIView within an animation block, the label animates its change in size as appropriate. However, the re-drawing of the text within it kind of 'jumps' -- and fair enough, i wouldn't expect the label to animate a change in the internal drawing of its text.
Anyway, what I'd like to do is fade out this label and perhaps fade in a second to avoid this jerkiness.
My question: Is there a good callback on UIView as to when it will respond to an auto layout change? or is that simply done in layoutSubviews?

Related

Why do these Auto Layout constraints for a UIView prevent UIButton subviews from receiving touch events?

I'm using auto layout, programmatically. I've got a simple UIViewController with a few controls, including two UIButtons arranged side-by-side. I often group related controls within a UIView, to act as a container, making the arrangement of groups-of-controls a bit easier to manage. You'll see that below with _iapButtonsView, which holds the two buttons and some spacers.
My question. In the following example, I was caught out by what I thought was a valid change to the constraints, that actually resulted in the UIButtons not receiving touch events.
Code extract - constraints in which the buttons do receive touch events:
- (void)viewDidLoad
{
[super viewDidLoad];
...
_buyButton = [ViewCreationHelper createRoundedBorderButtonBold];
[_buyButton addTarget:self action:#selector(buyTap:) forControlEvents:UIControlEventTouchUpInside];
_restoreButton = [ViewCreationHelper createRoundedBorderButton];
[_restoreButton addTarget:self action:#selector(restorePurchaseTap:) forControlEvents:UIControlEventTouchUpInside];
_iapButtonsView = [UIView new];
_iapButtonsView.translatesAutoresizingMaskIntoConstraints = NO;
[contentView addSubview:_iapButtonsView];
...
[_iapButtonsView addSubview:_buyButton];
[_iapButtonsView addSubview:_restoreButton];
// Constraints
NSDictionary* views = NSDictionaryOfVariableBindings(scrollView, contentView, iapDesciption, _iapButtonsView, _buyButton, _restoreButton, spacer1, spacer2, spacer3);
...
constraints = [NSLayoutConstraint
constraintsWithVisualFormat:#"V:|-25-[iapDesciption]-40-[_iapButtonsView]|"
options:0
metrics:nil
views:views];
[contentView addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-20-[_iapButtonsView]-20-|" options:0 metrics:nil views:views];
[contentView addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|[spacer1][_buyButton(==120.0)][spacer2(==spacer1)][_restoreButton(==_buyButton)][spacer3(==spacer1)]|" options:NSLayoutFormatAlignAllCenterY metrics:nil views:views];
[_iapButtonsView addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[_buyButton(==80.0)]|" options:0 metrics:nil views:views];
[_iapButtonsView addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[_restoreButton(==80.0)]|" options:0 metrics:nil views:views];
[_iapButtonsView addConstraints:constraints];
...
}
The constraints in question are the vertical constraints for _iapButtonsView. During development (this is an In-App Purchase screen) I had some debug controls at the bottom, which is why I had the trailing | connecting to the superview's bottom edge, like this:
constraintsWithVisualFormat:#"V:|-25-[iapDesciption]-40-[_iapButtonsView][someSpacer][someControls]|"
When I took those debug controls out, I changed those constraints to be:
constraintsWithVisualFormat:#"V:|-25-[iapDesciption]-40-[_iapButtonsView]"
thinking that was more correct: they're anchored from the top, only, the _iapButtonsView gets its size from its subviews (principally, the two buttons), so I shouldn't connect to the bottom edge of the superview...
With that change, the buttons no longer receive touch events. To experiment, I tried explicitly setting the vertical size of _iapButtonsView, but still not connecting to the bottom edge of the superview, e.g.
constraintsWithVisualFormat:#"V:|-25-[iapDesciption]-40-[_iapButtonsView(==80.0)]"
With those constraints, the buttons still do not receive touch events.
What am I not understanding?
(Edit: I removed the duplicated [contentView addSubview:_iapButtonsView]; in the code, above, per suggestion from daddy warbucks)
One issue, you've called this two times:
[contentView addSubview:_iapButtonsView];
Not sure if this helps, but it could be an issue.
Also, you don't have to use "(==80.0)", just use "(80.0)", or even "(80)" not sure if this helps, but hey, it could, right?

Adding a dynamically sized view (height) to a UIScrollView with Auto Layout

Here is my structure of views for this detail view (blogging application, I want to view the entire post which has dynamic height inside of a scrollview):
UIView
-UIScrollView
-SinglePostView (custom view)
-Title
-Subtitle
-Content
Normally to add a 'single post view' to a UIView I simply instantiate it, feed it my Post object and then add a single constraint that pins the width of the singlePostView to the superview, at which point things get laid out nicely. However when I try to add it to a scroll view, it doesn't show up nor does it scroll.
UIScrollView *scrollView = [[UIScrollView alloc] init];
[self.view addSubview:scrollView];
NOBSinglePostView *singlePost = [[NOBSinglePostView alloc] initWithPost:self.post];
[scrollView addSubview:singlePost];
singlePost.translatesAutoresizingMaskIntoConstraints = NO;
scrollView.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(scrollView,singlePost);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[scrollView]|" options:0 metrics: 0 views:viewsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[scrollView]|" options:0 metrics: 0 views:viewsDictionary]];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[singlePost]|" options:0 metrics: 0 views:viewsDictionary]];
In the structure you are presenting, using AutoLayout, the contentSize of your UIScrollView is driven by the intrinsicContentSize of its subviews, here your SinglePostView.
The problem is, SinglePostView being a subclass of UIView, its intrinsicContentSize is always CGSizeZero when considered by itself. What you need to do is make the intrinsicContentSize of your SinglePostView depend on the intrinsicContentSize of its subviews.
Then, because the subviews of your SinglePostView are UILabels, and because a UILabel's intrinsicContentSize is the smallest size it needs to display its content, your SinglePostView's intrinsicContentSize will be equal to the sum of its subviews intrinsicContentSizes, that is the total size needed to display the content of all three of your labels.
Here is how to do it.
Step 1: Removing all automatically set constraints
First, as you partially did, you need to remove all constraints automatically set by the system.
Assuming you don't have any constraints set in your storyboard or XIB (or you don't even have one of these), just do:
scrollView.translatesAutoresizingMaskIntoConstraints = NO;
singlePost.translatesAutoresizingMaskIntoConstraints = NO;
titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
subtitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
contentLabel.translatesAutoresizingMaskIntoConstraints = NO;
Now you have a clear slate and you can start setting your own constraints.
Step 2: Constraining the scrollView
First, let's create, as you did, the views references dictionary for AutoLayout to use:
NSDictionary *views = NSDictionaryOfVariableBindings(scrollView, singlePost, titleLabel, subtitleLabel, contentLabel);
Then, also as you already did, let's constrain the scroll view to be the size of its superview:
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[scrollView]-0-|" options:0 metrics:0 views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|-0-[scrollView]-0-|" options:0 metrics:0 views:views]];
Step 3: Constraining the SinglePostView to push the scrollView's contentSize
For this step to be clear, you have to understand that every constraints set between a UIScrollView and its subviews will actually change the contentSize of the UIScrollView, not its actual bounds. For Example, if you constrain a UIImageView to the borders of its parent UIScrollView and then put an image twice the size of the UIScrollView inside the UIImageView, your image won't get shrunk, its the UIImageView that will take the size of its image and become scrollable inside the UIScrollView.
So here is what you have to set here:
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[singlePost]-0-|" options:0 metrics:0 views:views]];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|-0-[singlePost]-0-|" options:0 metrics:0 views:views]];
[scrollView addConstraint:[NSLayoutConstraint constraintWithItem:singlePost
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:scrollView
attribute:NSLayoutAttributeWidth
multiplier:1.0f
constant:0.0f]];
First two constraints are pretty obvious. The third one, however, is here because, for your UILabels to display their content properly and still be readable, you will probably want them to be multilined and the scrolling to be vertical, not horizontal. That's why you set your SinglePostView's width to be the same as your scrollView's. This way, you prevent your scrollView's contentSize.width to be anything more than its bounds.width.
Step 4: Constraining your UILabels to "push" the bounds of your SinglePostView
Fourth and final step, you now need to set constraints on your SinglePostView's subviews, so that it gets an intrinsicContentSize from them.
Here is how you do it (simplest implementation, no margins, one label after the other vertically):
[singlePost addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[titleLabel]-0-|" options:0 metrics:0 views:views]];
[singlePost addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[subtitleLabel]-0-|" options:0 metrics:0 views:views]];
[singlePost addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[contentLabel]-0-|" options:0 metrics:0 views:views]];
[singlePost addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|-0-[titleLabel]-0-[subtitleLabel]-[contentLabel]-0-|" options:0 metrics:0 views:views]];
And with that you should be done.
One last advice, you should definitely look into UIStoryboard to do these kinds of things. It's a lot simpler and more visual.
Hope this helps,
P.S.: If you want, I can take some time and push a project using both UIStoryboard and the Visual Format Language on Github. Just tell me if you would need one.
Good luck.
in auto layout
frame of scrollview is decided by constraints between scrollview and superview of scrollview.
contentSize of scrollview is decided by constraints between scrollview and subview of scrollview.
you should set the size of singlePostView. ScrollView calculate contentSize from it. (you need to add size constraints explicitly)
CGFloat heightOfSinglePostView = calculate..
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[singlePost(heightOfSinglePostView)]|" options:0 metrics: 0 views:viewsDictionary]];

iOS Autolayout: How to move views when label text gets longer

I have a tableview cell with two labels and a small image.
If the labeltexts are short, all fits in one row like this:
.________________________________________.
| |
| [firstlabel] [img] [secondlabel] > |
|________________________________________|
However, if the labeltexts are getting longer, the image
and the second label should move to the second line:
.________________________________________.
| |
| [firstveryverylonglabel] > |
| [img] [secondverylonglabel] |
|________________________________________|
How would I do this with autolayout?
The first label is easy - just add constraints for left and top. Labels are always only one line heigh, and get truncated in the middle if the text gets way too long.
The image must always be in front of the second label (default space) horizontally, and both centered vertically. The image size should scale with the dynamic text font size (preferredFontForTextStyle:UIFontTextStyleBody) of the labels, so that if the user chooses large text the image also gets drawn larger.
The cell height should of course grow if two lines are needed.
Bonus Points if setting the necessary constraints would be possible in Interface Builder, but if not then I could set them with code in the init routine of the tableview cell.
My app should run under iOS 7 and later - no need for iOS 6. So I must compute the height in tableview:heightForCellAtIndexPath:, and will use a hidden cell to let Autolayout do its magic there.
I ended with setting constraints in code. I embedded the labels and the image in another view, then implemented -updateConstraints for the cell and the view.
In -tableView:heightForRowAtIndexPath:, I first let Autolayout make a first pass on the static hidden cell (just used for measuring) to set up the contentView by calling layoutIfNeeded, then force it to update the constraints by calling setNeedsUpdateConstraints followed by updateConstraintsIfNeeded, and finally measure the height of the cell with systemLayoutSizeFittingSize:UILayoutFittingCompressedSize.
In my view's updateConstraints method, I first try to arrange the cells side-by-side with
[self removeConstraints];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:
#"V:|-margin-[first]-margin-|"
options:0 metrics:metrics views:views]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:
#"H:|-margin-[first]-[image]-[second]-margin-|"
options:NSLayoutFormatAlignAllCenterY metrics:metrics views:views]];
Then I call systemLayoutSizeFittingSize:UILayoutFittingCompressedSize on the view and compare the width to the maximum possible space inside the contentView, given its fixed horizontal start position. If it's too wide, I need to set a two-line constraint set:
[self removeConstraints];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:
#"V:|-margin-[first]-[second]-margin-|"
options:0 metrics:metrics views:views]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:
#"H:|-margin-[first]-margin-|"
options:0 metrics:metrics views:views]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:
#"H:|-margin-[image]-[second]-margin-|"
options:NSLayoutFormatAlignAllCenterY metrics:metrics views:views]];
In the cell's updateConstraints method, I just call setNeedsUpdateConstraints on the view to make sure that the view is recalculated after the cell's size changed (e.g. when rotating portrait<=>landscape).
And that's it.

UIScrollView doesn't work with Autolayout (iOS 6)

I made a few UIScrollView's in different views, they all worked without Autolayout.
I turned Autolayout on, because it was better for my app.
But since then, there's a big problem with my UIScrollView's:
No one is scrolling, they don't work.
Here's my code for a UIScrollView:
.m:
-(viewDidLoad) {
scrollerHome.contentSize = CGSizeMake(320, 1000);
scrollerHome.scrollEnabled = YES;
[self.view addSubview:scrollerHome];
scrollerHome.showsHorizontalScrollIndicator = false;
scrollerHome.showsVerticalScrollIndicator = false;
[super viewDidLoad];
}
.h:
#interface ViewController : UIViewController{
IBOutlet UIScrollView *scrollerHome;
}
Do I have to add some code because I turned on Autolayout?
You should call [super viewDidLoad] before doing anything !
In autolayout, you do not set the contentSize manually. Autolayout works slightly differently with scrollviews, whereby the contentSize of the scroll view is dictated by the constraints of the scrollview's subviews.
If you're trying to force the contentSize to some large size (for example, you're implementing some infinite scroller), you can just add a subview of the appropriate size, e.g.:
UIView *containerView = [[UIView alloc] init];
containerView.translatesAutoresizingMaskIntoConstraints = NO;
[self.scrollView addSubview:containerView];
NSDictionary *views = NSDictionaryOfVariableBindings(containerView);
[self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[containerView]|" options:0 metrics:nil views:views]];
[self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[containerView(1000)]|" options:0 metrics:nil views:views]];
But if you were trying to set the contentSize in anticipation of adding subviews, you generally don't have to do anything, such as the above snippet. Just add your subviews, provide their constraints, and autolayout will adjust the scroll view's contentSize automatically.
As mentioned above, with autolayout, you can just add the subviews to your scrollview (with their constraints), and the contentSize will be calculated automatically for you.
There is a trick here, though. You sometimes you want to size a subview based upon the dimensions of the screen. But the usual technique of using the | symbols won't work. For example, for an imageview1 inside a scrollview, the usual #"H:|[imageview1]|" won't set the imageview1 to be the width of the screen, but rather it will define the scroll view's contentSize to match the width of imageview1, but it says nothing about what the width of that image view should be!
So, it's useful to capture a reference to the scroll view's superview. That way, you can use something like #"H:|[imageview1(==superview)]|", which not only says "make the scroll view's contentSize equal to the width of imageview1", but also "define the width of imageview1 to be equal to the width of the scroll view's superview."
Thus, for example, to add three images in a paging scroll view, you might do something like:
UIImageView *imageview1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"_DSC0004.jpg"]];
imageview1.contentMode = UIViewContentModeScaleAspectFit;
imageview1.translatesAutoresizingMaskIntoConstraints = NO;
[self.scrollView addSubview:imageview1];
UIImageView *imageview2 = ... // configured similar to imageview1
UIImageView *imageview3 = ... // configured similar to imageview1
UIView *superview = self.scrollView.superview;
NSDictionary *views = NSDictionaryOfVariableBindings(imageview1, imageview2, imageview3, superview);
// not only define the image view's relation with their immediate scroll view,
// but also explicitly set the size in relation to the superview, too!
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[imageview1(==superview)][imageview2(==superview)][imageview3(==superview)]|" options:0 metrics:nil views:views]];
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[imageview1(==superview)]|" options:0 metrics:nil views:views]];
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[imageview2(==superview)]|" options:0 metrics:nil views:views]];
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[imageview3(==superview)]|" options:0 metrics:nil views:views]];
self.scrollView.pagingEnabled = YES;
From the Apple iOS 6.0 release notes:
"In general, Auto Layout considers the top, left, bottom, and right edges of a view to be the visible edges. That is, if you pin a view to the left edge of its superview, you’re really pinning it to the minimum x-value of the superview’s bounds. Changing the bounds origin of the superview does not change the position of the view.
The UIScrollView class scrolls its content by changing the origin of its bounds. To make this work with Auto Layout, the top, left, bottom, and right edges within a scroll view now mean the edges of its content view."
You can find the full notes here and find the answer to your question in the section that I quoted from. They give code examples on how to use UIScrollView in a mixed Auto Layout environment.

How to resolve ambiguous layout?

I want an iPad layout that that has two panels side by side, to fill the width of the screen and both are as tall as the screen. My attempts have led to as follows
self.view addConstraints:
#"|[_sidePanel(300)]-1.0-[_mainPanel]|"
#"V:|[_sidePanel]|"
#"V:|[_mainPanel]|"
Inside __sidePanel_ I'm trying to create more constraints on child views.
Note the _sidePanel view is a UIScrollView.
I want to stack 2 views on top of one another in the side panel.
So I add the following constraints to__sidePanel_.
_sidePanelView addConstraints:
#"|[_top(300)]|"
#"|[_bottom(300)]|"
#"V:|[_top]-5.0-[_bottom]|"
It seems I need to specify the width for these two views in order to avoid ambiguity.
But I want the bottom view to fill the remaining space of __sidePanel_.
If I just pin __bottom_ to the bottom of __top_ (which gets a defined height at some point based on its contents) and to the bottom of its parent __sidePanel_, the __sidePanel_ and __bottom_ are both ambiguous; which makes sense i guess since the constraints are awfully similar (and which doesn't get avoided by adding the constraint for __bottom_ to the __sidePanel_ view as opposed to the topmost self.view).
If I hardcode a height for __bottom_, i resolve ambiguity but I don't want a defined height; i want it to fill remaining space in __sidePanel_.
Any suggestions on what I could try to resolve ambiguity but still achieve what I'm after?
You need to specify a height for either top or bottom -- it sounds like top gets a defined height at some point, but you need set a defined height for it initially, which you can change later.
Also, there's no need to specify the widths (300) for either top or bottom, since you've pinned them to the sides of sidePanel, which itself has a defined width. so these constraints worked fine with no ambiguity:
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"|[_sidePanel(300)]-1.0-[_mainPanel]|" options:0 metrics:nil views:viewsDict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[_sidePanel]|" options:0 metrics:nil views:viewsDict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[_mainPanel]|" options:0 metrics:nil views:viewsDict]];
[_sidePanelView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"|[_top]|" options:0 metrics:nil views:viewsDict]];
[_sidePanelView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"|[_bottom]|" options:0 metrics:nil views:viewsDict]];
[_sidePanelView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[_top]-5.0-[_bottom]|" options:0 metrics:nil views:viewsDict]];
self.topHeightCon = [NSLayoutConstraint constraintWithItem:self.top attribute:NSLayoutAttributeHeight relatedBy:0 toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:300];
[self.top addConstraint:self.topHeightCon];
Later, when you calculate the actual height for top, you can use self.topHeightCon.constant = (some value) to adjust its height.
In my case it came down to the fact that the view I was trying to have subviews constrain to its bounds was a UIScrollView, which wasn't happening. I since changed it to a UIView and voila my constraints work. And there you have it.

Resources