设计复杂的动画效果
制定统一的动画接口
动画中的高内聚低耦合原理:
如果一个类承担的职能过多,就等于把这些职能耦合在一起,一个职能的变化可能会削弱或者抑制其他职能的能力,这种耦合会导致脆弱的设计,当发生变化时,设计会遭到意想不到的破坏。如果想要避免这种现象发生,就要尽可能的遵守单一职能原则。
设计动画函数的注意事项
用里氏代换原则来处理动画类的继承问题
动画中的模块化设计
1.如果以下代码写在控制器中,实现动画的细节暴露在外,后续方便组合成复杂的动画效果很困难
- (void)viewDidLoad {
[superviewDidLoad];
// 初始化view
self.lineView = [[UIViewalloc]initWithFrame:CGRectMake(10,50,100,3)];
self.lineView.backgroundColor = [UIColorblackColor];
self.lineView.alpha =0.f;
[self.viewaddSubview:self.lineView];
// 延时2秒执行持续时间为1秒的动画 --> show
[UIViewanimateWithDuration:1delay:0options:UIViewAnimationOptionLayoutSubviewsanimations:^{
self.lineView.alpha =1.f;
self.lineView.frame =CGRectMake(10 +50, 50, 100, 3);
}completion:^(BOOL finished) {
}];
// 延时6秒执行持续时间为1秒的动画 --> hide
[UIViewanimateWithDuration:1delay:6options:UIViewAnimationOptionLayoutSubviewsanimations:^{
self.lineView.alpha =0.f;
self.lineView.frame =CGRectMake(10 +50 + 50, 100, 100, 3);
}completion:^(BOOL finished) {
}];
}
2.我们新建一个LineView类, 不要把实现动画的细节暴露在外,设计动画类尽量要符合单一职能原则,以便后续方便组合成复杂的动画效果
@interface LineView :UIView
@property (nonatomic)CGFloat offsetX;
// 显示动画
- (void)show;
// 隐藏动画
- (void)hide;
@end
#import "LineView.h"
@interface LineView ()
@property (nonatomic)CGRect rect;
@end
@implementation LineView
- (instancetype)initWithFrame:(CGRect)frame {
self = [superinitWithFrame:frame];
if (self) {
self.rect = frame;
}
return self;
}
- (void)show {
CGRect newRect =CGRectMake(self.rect.origin.x +self.offsetX,
self.rect.origin.y,
self.rect.size.width,
self.rect.size.height);
[UIViewanimateWithDuration:1animations:^{
self.frame = newRect;
}];
}
- (void)hide {
CGRect newRect =CGRectMake(self.rect.origin.x +self.offsetX +self.offsetX,
self.rect.origin.y,
self.rect.size.width,
self.rect.size.height);
[UIViewanimateWithDuration:1animations:^{
self.frame = newRect;
self.alpha =0.f;
}];
}
2.1 、在控制器中写如下
@property (nonatomic,strong)LineView *lineViewNew;
- (void)viewDidLoad {
//高内聚低耦合的写法
self.lineViewNew = [[LineViewalloc]initWithFrame:CGRectMake(10,200,100,3)];
self.lineViewNew.offsetX =50.f;
self.lineViewNew.backgroundColor = [UIColorblackColor];
[self.viewaddSubview:self.lineViewNew];
[self.lineViewNew show];
[selfperformSelector:@selector(excuteAfterDelay)withObject:nilafterDelay:6];
}
- (void)excuteAfterDelay {
[self.lineViewNew hide];
}