Reputation: 1053
I am trying to have a view scrim
fade in on top of everything in my view controller after 5 seconds once the initial view loads. This is what I have right now.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self setupAlarmPoll];
[self setupTimeLabel];
self.shouldRefresh = YES;
[self refreshSpotifyToken];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveNotification:)
name:@"backHome"
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveNotification:)
name:@"applicationDidEnterBackground"
object:nil];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[UIView animateWithDuration:2.00 animations:^{
self.scrim.hidden = NO;
}];
});
However, I don't get a gradual fade-in. The view just appears. How can I accomplish this animation in objective-c?
Upvotes: 1
Views: 1400
Reputation: 131398
The hidden
property of a view is not animatable. The alpha
property, however, is animatable.You need to:
By doing that you make the view no longer hidden, but completely transparent. The you animate the alpha property from 0.0 to 1.0, making the view fade in as desired.
The code would look like this:
self.scrim.alpha = 0;
self.scrim.hidden = NO;
[UIView animateWithDuration:2.00
delay: 5.0
options: 0
animations:^{
self.scrim.alpha = 1.0;
}
completion: nil
];
(Note that the long form of animateWithDuration takes a delay parameter, so you don't have to wrap it in a call to dispatch_after
.)
Also, why are you doing new development in Objective-C?
Upvotes: 2
Reputation: 437422
Either animate alpha
as others have mentioned, or use transitionWithView
with UIViewAnimationOptionTransitionCrossDissolve
:
- (void)viewDidLoad {
[super viewDidLoad];
self.scrim.hidden = true;
}
- (void)viewDidAppear:(BOOL)animated {
[UIView transitionWithView:self.scrim duration:2 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
self.scrim.hidden = false;
} completion:nil];
}
Upvotes: 2
Reputation: 8279
Yes, but it isn't isHidden
you are looking for, it's the alpha
property of the view. You see, isHidden
will just straight up declare if something is 100% not able to be seen at all or not. And as such you can not animate the isHidden
property of a UIView
. But this is where the alpha
property comes to the rescue, because it is intended to be used exactly as you are trying to with isHidden
. The alpha property determines how faded a UIView
is on screen. So if the alpha
is at 0
, it's hidden. So if you set your view's alpha
to 0
then use the follow code you can fade in the view:
// Swift
UIView.animate(withDuration: 0.25) {
view.alpha = 1
}
// Objective-C
[UIView animateWithDuration:0.25 ^{
self.view.alpha = 1.0;
}];
Upvotes: 2