How to react to UIControl resize when its data changes - ios

I've built a UIControl subclass to display a 1-month calendar view on
an iPhone. Most months require 5 weeks to display the dates, but
some months need 6, so I've built the control to dynamically resize
itself as needed. I'm using UIView animation to change the frame of
the control here.
The problem is, I now need the other controls on the screen to
move/resize when the calendar changes size. And I really need that
to happen with the animation of the calendar control changing size.
Ideally, I'd do this without coding a bunch of details in my calendar
control about other controls on the screen.
What's the best strategy here? I was hoping I could somehow anchor
the other controls to the frame of the calendar control and have the
platform adjust their location/size as it animates the frame change.
But, thus far, I can't find any combination of struts and springs to
make that happen.
Do I just need to bite the bullet and add my other on-screen controls
to the animation happening inside my calendar control?

I'll be interested to see if there are better answers to this.
At this point, all I know to do is override setFrame on your calendar view and when it changes, send setNeedsLayout to its superview.
But I'm not sure if standard views will autoresize this correctly. Generally geometry flows down the view tree, not up, and you want it to do both.
You may have to implement layoutSubviews on the containing view.

Move the animation logic out of the specific view and into a view controller that manages all of the controls. The view can still figure out its own proper size, and let the view controller ask. For instance:
[self.calendarView setDate:date];
CGSize calendarSize = [self.calendarView sizeForDate:date];
[UIView animateWithDuration:...
animations:^{
... re-layout everything, including the calendarView ...
}];
Another, similar approach:
[self.calendarView setDate:date];
[UIView animateWithDuration:...
animations:^{
[self.calendarView sizeToFit];
... re-layout everything else ...
}];
There are lots of similar approaches based on your preferences. But the key is to move the logic out of the specific view. Usually a view controller is the best solution. If the controls make a logical collection that could go into a single UIView, then you could have that "collection" UIView manage the same thing in its layoutSubviews, but it's more common that a view controller is a better solution here.

Thanks for the help. I tried both of these approaches with success. The override of setFrame and implementation of layoutSubviews worked, but the other controls jumped to their new locations rather than animating to those locations as the calendar control grew.
The approach of moving the other controls during the animation is what I had to go with. However, I wanted to keep the logic of the control pretty self-contained for re-use, so I left the animation in the control but added a delegate to react to size change, and put the delegate call inside the animation block. In full disclosure, I am also animating the new month's calendar onto the control while I'm growing the control, and this way I could do both of those things in the animation block.
So, the end code looks something like this:
// inside the calendar control:
[UIView animateWithDuration:0.5 animations:^{
self.frame = newOverallFrame; // animate the growth of the control
_offScreenCalendar.frame = newOnScreenFrame; // animate new month on screen
_onScreenCalendar.frame = newOffScreenFrame; // animate old month off screen
if (self.delegate)
{
[self.delegate handleCalendarControlSizeChange:newOverallFrame]; // animate other controls per the delegate
}
}];

Related

How to synchronize CALayer and UIView animations up and down a complex hierarchy

See How to manage CALayer animations throughout a hierarchy for a follow-up question that is concerned just with how to synchronize parent-child layer animations.
This is a design question concerning running dependent animations at different levels of the view hierarchy in response to animations up the hierarchy.
I have a container controller that has any number of child controllers. The parent controller organizes this content on the screen and at various points needs to change the size and positions of its children views.
I'm trying to animate each of these child views to transition its size/shape/position from their original starting point to the destination. A basic first pass with some basic animations starts to get the job done.
Things get more complicated though by the fact that some of the views being resized should also be performing animations on the contents of the view. Imagine a child view with centered content. As the child is shrunk or expanded, the centered content should be animated alongside the outer animation to compensate for the bounds changes so that the content stays centered.
To further complicate matters, I also have a mask layer for each child view that needs to be animated alongside the child’s animation. I also have some gestures that require NO animations to be used for transitions - so I need a way to sometimes animate the whole view/layer tree, and sometimes not.
So all of this gives me an architecture where I have something like the following
ContainerViewController.view
-> auxiliary and decorative views
-> WrapperView (multiple)
----> mask layer
-> Child controller view
-> subviews & layers
Now my question is really one of maintainability. I can animate each of these parts using explicit or implicit animations. What I need to figure out is what’s the best way to make sure that all of the animations being done are done using the same duration and timing function. At present, I trigger a lot of these off of property changes. In some cases the property changes come from layoutSubviews (triggered from setNeedsLayout).
So, what’s the best strategy for setting up these animations, especially the explicit ones. Is the best that I can do just picking up values from CATransaction? My fear is that not every property needs to be animated in every case (like in the auxiliary views) - I already am flipping setDisableActions on/off to force/deny some property animations.
Should CATransaction be used to trigger the setup of explicit view animations? How do I bind the parameters specified for a UIView animation to the parameters that will be used for the underlying layers? The following code seems to get the job done, but seems really ugly.
-(void) animateForReason:(enum AnimationReason) animationReason
animations:(void(^)()) animationBlock completion:(void(^)(BOOL)) completionBlock {
const auto animationDuration = 3.0; // make this long to be noticeable!
[UIView animateWithDuration:animationDuration delay:0 options:UIViewAnimationOptionLayoutSubviews
animations:^{
[CATransaction begin];
[CATransaction setAnimationDuration:animationDuration];
animationBlock();
[CATransaction commit];
}completion:completionBlock];
}
I think that UIViewControllerTransitionCoordinator is out because I need to do all of these animations in response to user actions, not just external things, like rotations or frame changes.
There are a few options to consider:
For UIView transitions, you can pass the UIViewAnimationOptionLayoutSubviews option. This will animate the changes between subviews before and after calling layoutSubviews on the view whose frame you just changed.
Instead of using layoutSubviews at all, you could override setBounds: or setFrame: on your UIView and CALayer subclasses. This way, if they're called within an animation block, the subviews will animate together with the superview. If they're not called within an animation block, they'll update instantly.
My fear is that not every property needs to be animated in every case (like in the auxiliary views) - I already am flipping setDisableActions on/off to force/deny some property animations.
Generally, if you want it animated, put it in an animation block, and if you don't, don't. Obviously, it can get more complex than this, which is why Apple sometimes has a setter with an animated argument (like setSelected:animated:).
If you have sometimes on, sometimes off properties, follow this pattern yourself. One possible implementation:
- (void) setNumberOfWidgets:(int)widgetCount animated:(BOOL)animated {
BOOL oldAnimationValue = [UIView areAnimationsEnabled];
if (!animated) {
[UIView setAnimationsEnabled:NO];
}
// a related property which may or may not cause an animation
self.someOtherProperty = someValue;
if (!animated) {
[UIView setAnimationsEnabled:oldAnimationValue];
}
}
My question is really one of maintainability.
Yes, it sounds like you're thinking about some kind of giant object that manages all the animation possibilities for you. Resist this temptation. Let each view be responsible for animating its own subviews, and tell a view (don't let it ask) whether or not these changes should be animated.
I think that UIViewControllerTransitionCoordinator is out because I need to do all of these animations in response to user actions, not just external things, like rotations or frame changes.
Yes, that's correct. Don't use UIViewControllerTransitionCoordinator for this.

UIView not redrawing, but elements become misplaced

I'm having an issue with my app's layout which is a bit tricky to explain. When the app first starts, this is what I'm showing:
After the user taps "Create Profile", I animate those buttons and show a registration form instead:
Needless to say, the buttons are now not in their "natural" position. Note, however, that the text fields are - that's where I have placed them in the storyboard, but when the view first loads I hide them. The animations are working great, but then I needed to scroll my view up when the user gives focus to a text field and the keyboard hides the field. The details of how to trigger the bug are a bit hard to explain, so I managed to boil it down to what seems to be a redraw event, except that it isn't... Let me try and explain that.
First of all, here's what happens when the keyboard is about to show:
- (void)keyboardWillShow:(NSNotification*)notification
{
CGRect frame = self.view.frame;
frame.size.height -= 1;
self.view.frame = frame;
}
Notice that this is a test only, probably the minimal I found that would still trigger the bug. All it does is resize the view. I would expect the view to be exactly as it was, with one less pixel, right? Wrong. Here's what I get:
That is, all elements returned to their "natural" positions, completely ignoring their previous positions. My first guess was that it would seem that the window is redrawing, so I tried this:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
NSLog(#"View was drawn");
}
But this only triggers when the window is first drawn, not when this strange behaviour happens. To understand what I mean by "natural position", here's what I have in storyboard:
You can also see that I'm not using constraints and the underlying structure of my view:
The full code for the entire setup is quite extensive, so pretty much not practical at all to show. However, how I animate the subviews resumes to changing their frame as I did in keyboardWillShow, and setting their positions to whatever I need.
Any ideas?
So you're using storyboards and you have "Use AutoLayout" set to false for your entire storyboard?
In that case your app is using "struts and springs" style placement rules. You're going to have to debug those.
It's a bit hard to describe everything in a view controller in a post. It's easier to go over it in IB. Perhaps you can write a utility function that logs all the autoresizingMask values for the views in your view controller, and go over those, and perhaps post them here describing the autoresizingMask values for each view in your original post.

making the uipagecontrol animation look like uinavigationcontrol animation

I'm using the concept of the ui page control.
For example, I have multiple similar views. Let say 10 news articles. I put them in a a page control and am able to swipe between them.
However, I want to mimic the animation that the UINavController does. Is this possible? ie: not have the pages scroll end to end but instead a slight overlap and effect where one panel slides out at twice the speed of the one below it sliding in.
Any Ideas?
If i am not getting wrong understanding of your question..
As this is not possible to do with existing page controls you need your own logic
This is how it should be handled, you will need to adjustments as per your requirement..
Rough logic
[self.view addSubview:nextArticleView];
nextArticleView.frame = // set offscreen frame, in the direction you want it to appear from
//Set more time as newArticle should overlap to existing articles view
[UIView animateWithDuration:10.0
animations:^{
nextArticleView.frame = // desired end location (current articles initial frame)
}];
//set less time as current article should slide fast
[UIView animateWithDuration:5.0
animations:^{
self.view.frame = // desired end location (off screen)
}];

UIView switching animation for landscape and portrait scene in storyboard?

I'm trying to design different layouts for my view controller. After googling, I've got this answer from SO. Basically, the answer instructs me to setup 2 scenes, one for landscape and one for portrait, when the device rotates, hide one and show the other one.
And my question is what if I want to add a sweet animation for the rotation process? For example, since I can setup the same view on different scenes, can I set the motion path for these views and disappear? Or, if it is easier, can I add some rotation and fade out animation?
I'm quite green with Core Animation, so a detailed explanation is very useful for me. Big big thanks in advance!
There are a few options here. The main methods you are looking for to do any of this are:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration;
and
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation;
If you want to move the elements around the screen while the rotation is happening you will be best off changing the frames of the elements rather than creating a separate view file. Using any motion animation would require some mapping between the two and I have never heard of anything like this before. Again, if you just change the frames though, you can preform basically any screen movements you would like (for views and subviews).
To do the fading you could just throw an animation block in the first method:
[UIView animateWithDuration:duration
animations:^{
// set alphas for old and new views here.
}];

iOS Retractable Menu

I am currently developing an app that contains a music player. As of now it has a play, pause, & a select song button that shows the current song playing. Right now, the player is always on the screen. I want to make it so theres a button in the middle of the page so that when users click that, the whole media player with the play, pause, and select song button/icon will appear. When they click on that middle button again it shall hide those icons.
If anybody could point me in the right direction whether it be tutorials already out, or other discussions (I could not find any ones really) that would be awesome!
NOTE: I'm not trying to make the popover menu that facebook uses. This menu/audio player will expand/retract horizontally over the current view
Thank you in advance!!!!
Sounds like you need to look into the .hidden property of view objects (allows you to make views visible/not-visible), and possibly the ability to move views around on the screen with the .frame property (setting location, height/width).
Without some more detailed information about the effect you're trying to achieve, it's difficult to say more than that. If you use interface builder to set up the view/UI-objects you want to display, you can simply set the base view to hidden in interface builder and then when the user clicks your button set .hidden=NO for that view.
Note: to be able to show/hide everything as a unit like this, I'm assuming that you use a single UIView object in interface builder as the container (sized and placed where you want it) and then add your controller buttons as sub-objects inside that single view. This allows you to show/hide everything by just setting .hidden property for the containing view.
I'm not exactly sure what visual effect your looking for, but I think you already said it - just hide them.
You can do that a couple of ways.
One simple way is just to put those elements inside of their own view. Use a storyboard or xib file. Put your buttons and controls you want to hide show in a view.
Then create a reference in your view controller to that view. call it controlsView.
#property (strong,nonatomic) IBOutlet UIView *controlsView;
Make sure you connect that view.
Then when the button is pushed, just hide that entire view:
self.controlsView.hidden = YES;
When pushed again, show it:
self.controlsView.hidden = NO;
If you want a bit smoother look and feel, wrap it in an animation like this:
//to hide
[UIView animateWithDuration:2 animations:^{
[self.controlsView setAlpha:0];
} completion {
self.controlsView.hidden = YES;
}];
//to show
self.controlsView.alpha = 0;
self.controlsView.hidden = NO;
[UIView animateWithDuration:2 animations:^{
[self.controlsView setAlpha:1.0];
} completion {
}];
hope that helps

Resources