我是动画新手,尝试编写自定义segue以实现从左到右滑出侧边菜单,覆盖主视图,占据屏幕的一半。
有一个自定义的segue代码:
#import "CustomSegue.h"
@implementation CustomSegue
- (void)perform {
UIViewController *contentVC = self.sourceViewController;
UIViewController *sideBarVC = self.destinationViewController;
CGRect sideFrame = sideBarVC.view.frame;
[sideBarVC.view setFrame: CGRectMake(0, 0, 0, contentVC.view.frame.size.height)];
CGRect animationFrame = contentVC.view.frame;
sideFrame = sideBarVC.view.frame;
animationFrame.size.width = contentVC.view.frame.size.width / 2;
[UIView animateWithDuration:0.3
delay:0.0
options:UIViewAnimationOptionCurveEaseOut
animations:
^{
sideBarVC.view.frame = animationFrame;
}
completion:
^(BOOL finished) {
sideBarVC.view.frame = animationFrame;
contentVC.view.alpha = 0.5f;
[[contentVC.view superview] addSubview:sideBarVC.view];
}];
}
@end
我添加一些变量来查看框架是否正确,并且在更改框架时它是正确的。
但是我看不到我的“预期”动画:sideBarVC.view.frame = animationFrame;
有人可以帮忙吗?感谢。
答案 0 :(得分:1)
如果要从左到右动画制作幻灯片,首先必须将动画视图框架的原始X设置为负值,然后在动画块中将原始x设置为这样的事情。
sideFrame = sideBarVC.view.frame;
sideBarVC.view.frame = CGRectOffset(sideFrame, - contentVC.view.frame.size.width, 0);
[[contentVC.view superview] addSubview:sideBarVC.view];
[UIView animateWithDuration:0.3 animations:^{
sideBarVC.view.frame = sideFrame;
contentVC.view.alpha = 0.5f;
} completion:nil];
使用您的代码我不会看到动画发生,因为sideBarVC.view
被添加到动画的完成块中。到那时,动画已经完成,sideBarVC.view
被添加为子视图并且其框架已设置。
答案 1 :(得分:0)
突然说,我误解了这个立场。使用下面的代码可以实现动画,
但它仍有一个问题,侧栏菜单位于屏幕顶部的导航工具栏下方。有谁知道如何解决它?
- (void)perform {
UIViewController *contentVC = self.sourceViewController;
UIViewController *sideBarVC = self.destinationViewController;
CGRect sideFrame = sideBarVC.view.frame;
[sideBarVC.view setFrame: CGRectMake(-(contentVC.view.frame.size.width), 0, contentVC.view.frame.size.width/2, contentVC.view.frame.size.height)];
CGRect animationFrame = contentVC.view.frame;
sideFrame = sideBarVC.view.frame;
animationFrame.size.width = contentVC.view.frame.size.width / 2;
sideBarVC.view.alpha = 0;
[[[contentVC.view superview] window] addSubview:sideBarVC.view]; < -- this is important, not [superview addSubView]
[UIView animateWithDuration:1
delay:0.0
options:UIViewAnimationOptionCurveEaseOut
animations:^{
sideBarVC.view.frame = animationFrame;
sideBarVC.view.alpha = 1;
}
completion:^(BOOL finished) {
sideBarVC.view.alpha = 1;
sideBarVC.view.frame = animationFrame;
}];
答案 2 :(得分:0)
适用于Swift 3
override func perform() {
let contentVC = self.sourceViewController;
let sideBarVC = self.destinationViewController;
var sideFrame = sideBarVC.view.frame
sideBarVC.view.frame = CGRect(x: -(contentVC.view.frame.size.width), y: 0, width: contentVC.view.frame.size.width/2, height: contentVC.view.frame.size.height)
sideFrame = sideFrame.offsetBy(dx: -1 * contentVC.view.frame.size.width, dy: 0)
contentVC.view.superview?.addSubview(sideBarVC.view)
UIView.animate(withDuration: 0.3) {
sideBarVC.view.frame = sideFrame
contentVC.view.alpha = 0.5
}
}