简体   繁体   中英

Animating a UIView in a .xib file

I've made a program in Xcode that tells the time. I want to have a rectangle that animates/grows longer as the seconds increase (time progresses), and starts again when the seconds reach 60 (and go back to 0). I don't have storyboarding and have already started so I don't want to go back and start again.

Should I use a UIView instance and animate the 'frame' property?

Here is my clock code:

- (void)viewDidLoad
{
[self updateTime];

[super viewDidLoad];

hourFormatter = [[NSDateFormatter alloc] init];
hourFormatter.dateFormat = @"HH";
minuteFormatter = [[NSDateFormatter alloc] init];
minuteFormatter.dateFormat = @"mm";
secondFormatter = [[NSDateFormatter alloc] init];
secondFormatter.dateFormat = @"ss";    
}

- (void)updateTime {

[updateTimer invalidate];
updateTimer = nil;

currentTime = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setTimeStyle:NSDateFormatterMediumStyle];

hourLabel.text = [hourFormatter stringFromDate: currentTime];
minuteLabel.text = [minuteFormatter stringFromDate: currentTime];
secondLabel.text = [secondFormatter stringFromDate: currentTime];

updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
}

Yes, you can use a UIView and animate its frame.

You shouldn't necessarily do this using a timer though, just set the animation to run for the full duration and the complete frame height change and use a timer to restart the next animation. This will give the smoothest animation.

For updating the time display you only need a timer running once per second.

Look at running the animation like this:

CGRect frame = self.expandingTimeView.frame;
frame.height = 0;
self.expandingTimeView.frame = frame;

[UIView animateWithDuration:60
                 animations:^{
    frame.height = MAX_FRAME_HEIGHT;
    self.expandingTimeView.frame = frame;
}];

There's a good guide here .

This code would go in your updateTime method, which I'm assuming would be called each minute by a timer. You need to correct the name of expandingTimeView for whatever your view property is called, and you need to replace MAX_FRAME_HEIGHT with the maximum height the view should grow to during the animation.

You may want to have 2 methods, 1 containing the view animation ( updateTimeView ), called each minute and 1 containing the label text update ( updateTimeLabels ), called each second. In this case the 2 timers should be created in viewWillAppear:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM