设计动画函数的注意事项
1.动画方法的命名统一
2.预留非动画情形的设计
3.用百分比来表示动画的执行程度
4.懒加载的使用
继续对LineView进行改进
@interface LineView :UIView
@property (nonatomic)CGFloat offsetX;
// 显示动画
- (void)showWithDuration:(CGFloat)duration animated:(BOOL)animated;//非动画情形的设计
// 隐藏动画
- (void)hideWithDuration:(CGFloat)duration animated:(BOOL)animated;
// 创建view
- (void)buildView;
// 动画百分比(手动设置动画的程度)
- (void)percent:(CGFloat)percent;
@end
#import "LineView.h"
@interface LineView ()
@property (nonatomic)CGRect startRect;
@property (nonatomic)CGRect midRect;
@property (nonatomic)CGRect endRect;
@end
@implementation LineView
- (instancetype)initWithFrame:(CGRect)frame {
self = [superinitWithFrame:frame];
if (self) {
self.alpha =0.f;
}
return self;
}
// 显示动画
- (void)showWithDuration:(CGFloat)duration animated:(BOOL)animated {
if (animated == YES) {
[UIViewanimateWithDuration:duration animations:^{
self.frame =self.midRect;
self.alpha =1.f;
}];
}else {
self.frame =self.midRect;
self.alpha =1.f;
}
}
// 隐藏动画
- (void)hideWithDuration:(CGFloat)duration animated:(BOOL)animated {
if (animated == YES) {
[UIViewanimateWithDuration:duration animations:^{
self.frame =self.endRect;
self.alpha =0.f;
}completion:^(BOOL finished) {
self.frame =self.startRect;
}];
}else {
self.frame =self.startRect;
self.alpha =0.f;
}
}
// 创建view
- (void)buildView {
// todo
self.startRect =self.frame;
self.midRect =CGRectMake(self.startRect.origin.x + self.offsetX,
self.startRect.origin.y,
self.startRect.size.width,
self.startRect.size.height);
self.endRect =CGRectMake(self.startRect.origin.x + self.offsetX *2,
self.startRect.origin.y,
self.startRect.size.width,
self.startRect.size.height);
}
// 动画百分比(手动设置动画的程度)
- (void)percent:(CGFloat)percent {
CGFloat tmpOffsetX = 0;
if (percent <= 0) {
tmpOffsetX =0;
}else if (percent >=1) {
tmpOffsetX =self.offsetX;
}else {
tmpOffsetX = percent *self.offsetX;
}
self.frame =CGRectMake(self.startRect.origin.x + tmpOffsetX,
self.startRect.origin.y,
self.startRect.size.width,
self.startRect.size.height);
}
@end
2.在控制器中写如下
- (void)viewDidLoad {
[superviewDidLoad];
self.lineView = [[LineViewalloc] initWithFrame:CGRectMake(10,100, 100, 3)];
self.lineView.backgroundColor = [UIColorredColor];
self.lineView.offsetX =50;
[self.lineViewbuildView];
[self.viewaddSubview:self.lineView];
[selfperformSelector:@selector(delayShow)
withObject:nil
afterDelay:3.f];
[selfperformSelector:@selector(delayHide)
withObject:nil
afterDelay:5.f];
}
- (void)delayShow {
[self.lineViewshowWithDuration:1.fanimated:YES];
}
- (void)delayHide {
[self.lineViewhideWithDuration:1.fanimated:YES];
}