Complex layout in UIView that animates its content - ios

I'm having this general question about a problem that arises very often when I'm designing complex UIViews that require a special layout and animations at the same time.
What I'm currently building is the same kind of view that the Mail app uses on iOS to present a list of recipients when writing an email (the blue badges container) :
So I understand and know how I would build such a view, but I always have this question when facing such a case : How do you handle the complex layout (layouting all the blue rounded rectangles) and their animations at the same time (when adding or removing a recipient) ?
1. Normally I would reimplement :
- (void)layoutSubviews
to reflect the state of the view at the layout moment (ie layout each blue rounded UIButton side by side) according to my current bounds and just add and animate a UIButton when someone adds a new person to the list.
But what would happen to the animation if a layout pass is already running? (this may be a dumb question since everything is supposed to happen on the main thread and so no concurrency is involved here, but I'm not sure on how to handle this)
I think those two things (layout and animations) are not supposed to happen at the same time, since the main runloop "enqueues work and dequeues work" one "block" at a time (but maybe an animation is just hundreds of blocks enqueued that draw different things overtime, which could easily be compromised by a layout block in between??)
2. Also, would this solution be acceptable ?
Reimplement layoutSubviews the exact same way to handle the correct layout of my subviews
When someone adds or deletes a person, just call this to re-position everything animated
[UIView animateWithDuration:0.25f animations:^{
[self setNeedsLayout];
[self layoutIfNeeded];
}];
As you can see, lots of questions here, I don't know exactly how to handle this gracefully.
Both of these solutions have been tested and approved but the thing is which one is the best ?
Do you have a better solution ?
Thanks for your help!

As I understood, you mean animations applied to a view for which layoutSubviews method is implemented, e.g. animated change of its frame. If something is changed in your view while animation is ongoing that causes the view to re-layout, then layoutSubviews method will be called.
Basically, such kind of animations is nothing more than following:
change view's frame (actually, frame of a view's layer) by some small value (e.g. increase origin's Y coordinate by 1 pixel)
call layoutSubviews, if needed
redraw view (i.e. its layer)
change view's frame by some small value
call layoutSubviews, if needed
redraw view
...
repeat steps above until view's properties reach target values
All those steps are performed on the main thread, so steps above are consecutive and are not concurrent.
Generally speaking, the layoutSubviews method should define coordinates and sizes of subviews basing on its own bounds. Animations change the view's frame and correspondingly its bounds, so your implementation of the layoutSubviews method is supposed to handle those changes correctly.
That is, the answer for your question is implement correctly layoutSubviews method.
P.S. This answer has a great explanation of how animations are implemented.
Update
It seems that previously I understood the question incorrectly. My understanding was:
What happens if layoutSubviews method is called for a view being animated?
That is, I assumed that there is some view which e.g. changes its y coordinate with animation, the layoutSubviews method is called for this view during animation, and some subview of the view changes its position in the layoutSubviews.
After clarification from #Nicolas, my understanding is as follows:
Let's have some view ('Parent') with a subview ('Child'); let's animate this subview ('Child'); let's call layoutSubviews method of the 'Parent' view and change 'Child' subview's frame in this layoutSubviews method while animation is ongoing. What will happen?
Background Theory:
UIView itself doesn't render any content; it's done by Core Animation layers. Each view has an associated CALayer which holds a bitmap snapshot of a view. In fact, UIView is just a thin component above Core Animation Layer which performs actual drawing using view's bitmap snapshots. Such mechanism optimizes drawing: rasterized bitmap can be rendered quickly by graphics hardware; bitmap snapshots are unchanged if a view structure is not changed, that is they are 'cahced'.
Core Animation Layers hierarchy matches UIView's hierarchy; that is, if some UIView has a subview, then a Core Animation layer corresponding to the container UIView has a sublayer corresponding to the subview.
Well... In fact, each UIView has even more than 1 corresponding CALayer. UIView hierarchy produces 3 matching Core Animation Layers trees:
Layer Tree - these are layers we used to use through the UIView's layer property
Presentation Tree - layers containing the in-flight values for any running animations. Whereas the layer tree objects contain the target values for an animation, the objects in the presentation tree reflect the current values as they appear onscreen. You should never modify the objects in this tree. Instead, you use these objects to read current animation values, perhaps to create a new animation starting at those values.
Objects in the render tree perform the actual animations and are private to Core Animation.
Change of UIView's properties such as frame is actually change of CALayer's property. That is, UIView's property is a wrapper around corresponding CALayer property.
Animation of UIView's frame is actually change of CALayer's frame; frame of the layer from Layer Tree is set to the target value immediately whereas change of frame value of layer from presentation tree is stretched in time. The following call:
[UIView animateWithDuration:5 animations:^{
CGRect frame = self.label.frame;
frame.origin.y = 527;
self.label.frame = frame;
}];
doesn't mean that self.label's drawRect: method will be called multiple times during next 5 seconds; it means that y-coordinate of the presentation tree's CALayer corresponding to the self.label will change incrementally from initial to target value during these 5 seconds, and self.label's bitmap snapshot stored in this CALayer will be redrawn multiple times according to changes of its y-coordinate.
Answer:
Given this background, now we can answer the original question.
So, we have ongoing animation for a child view, and layoutSubviews method gets called for a parent view; in this method, child view's frame gets changed. It means that frame of a layer assiciated with the child view will be immediately set to the new value. At the same time, layer from the presentation tree has some intermidiate values (according to ongoing animation); setting new frame just changes target value for presentation tree layer, so that animation will continue to the new target.
That is, result of situation described in the original question is a 'jumping' animation. Please see demonstration in the GitHub sample project.
Solution for such complex cases
In your layoutSubviews method, if an animation is ongoing, you need to use in-flight animation coordinates. You can obtain them with the presentationLayer method of CALayer associated with a view. That is, if a view being animated is called aView, then presentation layer for this view can be accessed using [aView.layer presentationLayer].

Related

Animating UIView based on as-yet undetermined layout

I have a custom view, CustomView, that can animate itself in response to an animate message:
// in a view controller
[self.customView animate];
Inside -[CustomView animate], the logic is as follows:
- (void)animate {
for each subview {
startFrame = subview.frame;
endFrame = EndFrameFromStartFrame(startFrame);
subview.animation = AnimationLoopBetween(startFrame, endFrame);
}
}
* This block is pseudocode.
That is to say, the animate method examines the current frame of each subview and generates an animation ending frame for each subview which is essentially a frame which is a fixed ratio larger than the current frame. Then, it creates one animation per subview that varies the frame of its subview, alternating between the current (or start) frame and the end frame, calculated earlier.
This method works very well in general. It allows CustomView to animate properly regardless of how its superview positions and sizes it.
However, in a few cases, "users" of CustomView (that is, view controllers) call animate very early in their lifetime – so early, in fact, that Auto Layout has not yet made any constraint or layout passes. This means that animate is called when all of CustomView's subview frames are CGRectZero. As you can probably guess, this causes both the starting and ending values of the animations to be calculated incorrectly.
Even after the layout pass is complete, and the views' model layers have the proper frames, the CustomView instance is still not visible, because its subviews are happily animating from one zero-rect to another. Not good.
How should I restructure this animation behavior to allow users of this class to call animate at any time without negative repercussions?
Here are some possible answers I've considered, and why they don't seem satisfactory to me:
In any view controller that uses CustomView, put off the call to animate until viewDidLayoutSubviews.
This forces an unwieldy restriction on view controllers that use this view.
In CustomView's layoutSubviews method, first call [super layoutSubviews], then restart the animation if it was already running.
An interesting idea, but CustomView has more than one level of subviews. Thus, even after [super layoutSubviews], many of the views further down the view hierarchy will not yet have valid frames, meaning animate will still misbehave.
In CustomView's layoutSubviews method, first call [super layoutSubviews], then manually layout any required views' frames using [<view> layoutIfNeeded], before finally restarting the animation if it was already running.
This might actually work, but doesn't seem like a good idea. As much as possible, I'd like to leave layout work to Auto Layout.
Why not just skip the uninteresting case?
- (void)animate {
if (CGRectEqualToRect(self.frame, CGRectZero) return;
// ...animate.
}

GLKit's -drawRect: is not called during screen rotation

I have GLKit-based app with some simple object displayed.
All works fine, except screen rotation, during which GLKView is not updated (-drawRect: is not called). So during rotation projection matrix is not updated according to dynamically changing screen sizes and object looks badly (stretched).
This might be a shot in the dark since I don't have any experience with GLKit, however I do have experience with UIView and -drawRect:. Try changing the contentMode of the view in question to redraw:
view.contentMode = UIViewContentModeRedraw;
This will tell the view that it needs to redraw it's contents when it's boundaries change. Otherwise, UIView will simply attempt to scale it's contents (the default for contentMode is UIViewContentModeScaleToFill). The reason for this is that it's a lot easier to scale what's there than to redraw the contents and UIView is designed to be as efficient as possible.
That's simply not how UIKit animations work. I sort-of explain how half of it works in this answer, but I'll try to summarize the relevant bits:
Everything is a textured rectangle. (There are some exceptions, like perhaps CAShapeLayer, but this is true for the most part.)
UIView's properties are linked to CALayer's "model tree" properties. They change instantaneously.
Animations work by animating the "presentation tree" properties from the starting value to the current model value.
The starting value of the animation is, by default, the previous model value. Specifying UIViewAnimationOptionBeginFromCurrentState makes it use the current presentation value.
There are, of course, a few exceptions (CAShapeLayer seems to be more than a textured rect, UIScrollView does scrolling animations on a timer, UIView transitions are another thing entirely...).
How rotation is supposed to work is that you get a single -setFrame:, everything is laid out (and potentially rerendered), and then the animatable properties are animated. By default, this means things will rerender to the new dimensions but get stretched to fit the old dimensions, and then animate (and unstretch) as the rotation progresses.
That said, GLKView might work differently. If you're using GLKViewController, it might even suspend rendering during the rotation animation. You could try calling -setNeedsDisplay during the rotation, but it won't help much since the frame is already set to its final value.
Probably the easiest way to handle the rotation animation yourself is to force a non-animated relayout to the rotated frame and then do some fudging in the renderer (the black border and status bar animate separately though).
Alternatively, the traditional way is to make your VC portrait-only and handle the device orientation notifications yourself, but this is a big can of worms (you then have to worry about the status bar orientation which determines things like the touch offset and keyboard orientation, and it tends to interacts "interestingly" when transitioning to/from other VCs).
First of all, ensure that at some point early in your application lifecycle, enable device orientation changes.
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
Then when your view is instantiated register for a notification like so.
[[NSNotificationCenter defaultCenter] addObserver: self selector: #selector(deviceOrientationDidChange:) name: UIDeviceOrientationDidChangeNotification object: nil];
Then implement -deviceOrientationDidChange: in your view controller and call -setNeedsDisplay

Notification when visible area of CALayer changes?

I have a CALayer for which I provide content for only the visible area (somewhat similar to CATiledLayer). The problem is there does not seem to be a way to receive notification when the visible area of the CALayer changes so that displayLayer is called. I currently subclass and hook setPosition, setBounds, and setTransform, but this doesn't catch the cases where a superview/layer changes (for example, UIScrollView scrolls by changing the scroll views origin ). I'm left hooking parent views and sprinkling setNeedsDisplay all over the code.
Is there a better way?
The currently visible rect is [CALayer visibleRect]. This is set by the scroll view (layer) and is what you're expected to base drawing on in scroll views.
You probably want to override -needsDisplayOnBoundsChange to return YES. That's typically how you handle most of what you're describing.
If you want things like position to force a redraw (that's unusual, but possible), then you can override +needsDisplayForKey: to return YES for any key changes that you want to force a redraw.
If you want to make sure you're only drawing what you need to draw, then you should be checking your clipping box using CGContextGetClipBoundingBox() during your drawing code.

UIViewContentModeRedraw vs setNeedsDisplay?

I don't know the difference between setneedsdisplay and uiviewcontentmoderedraw, when would you use each, aren't they the exact same thing?
They are different things. setNeedsDisplay is a verb. Use it to tell a view that the state of the stuff it's viewing has changed, so it should redraw (by calling its drawRect: method on the next iteration of the run loop).
contentMode is an attribute of a view. It doesn't cause the view to do anything immediately. It specifies how the view handles its content relative to its size. UIViewContentModeRedraw is a value that might be assigned to this property. It means that the view will render size changes by causing itself to redraw (by invoking setNeedsDisplay on itself).
If you plan to animate alteration of your view's size, UIViewContentModeRedraw is an expensive choice because it will try to repeatedly redraw from scratch during the animation (rather than manipulating a bitmap copy).

How to set a background pattern for a large UIScrollView (that scrolls with the view)

Seems like a very simple problem! But I'm having great difficulty.
My ideas and attempts so far:
scrollView.backgroundColor = [UIColor colorWithPatternImage:myImage]]
Doesn't scroll with contents
Create UIView the size of contentSize (actually, larger due to elastic bounces on scroll view), and use pattern as above on this sub view of UIScrollView.
Causes massive memory hit (and crash) when UIView gets too large. See also: Large UIScrollView with background pattern fails
Similar to (2), exept I only create a UIView the size of the maximum number of repetitions of the background image that will be seen, and cleverly move the view to wherever is needed to show the correct background repetitions.
Causes this background view to shift left and right unexpectedly when animating the scroll.
Create UIView subclass and override drawRect. Use various Core Graphics techniques to draw content by hand.
Not animatable. Implementing my own contentOffset property isn't a standard Core Animation property.
Overriding drawRect on UIScrollView doesn't respect the content offset, and doesn't get called multiple times as it scrolls/animates. The rect parameter is always simply the bounds of the UIScrollView.
As with (4), except I set the bounds.origin of my UIView subclass in my setContentOffset implementation, since it's an animatable property.
drawRect doesn't seem to get called every frame.
Use CATiledLayer, as suggested in this answer: Large UIScrollView with background pattern fails. Implementation details here: http://www.cimgf.com/2011/03/01/subduing-catiledlayer/.
I really don't want the ugliness of seeing tiles asynchronously being drawn as user scrolls. It's just a simple background pattern!
This seems like the simplest thing! Why is it so hard!?
Maybe the sample code:ScollViewSuit->3_Tiling can help you. You can search it in the official docset.
This works like CATiledLayer but only use UIKit, the tile was loaded on the main thread.
And I really don't think this is a good solution.

Resources