标签:位置 保存 ddc add 部分 const function animation origin
实现一个简单的呈现/解散动画效果,当呈现时,呈现的主要内容和背景要明显区分,背景呈现一个半透明遮罩效果,透过背景可以看到下层 View Controller 的内容:
呈现控制器即要弹出另外一个控制器的 View Controller。本例中即 ViewController 类。当呈现时,使用如下代码:
// 1
UIStoryboard* sb=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
ModalController* vc = [sb instantiateViewControllerWithIdentifier:@"modal"];
// 2
vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
// 3
[self presentViewController:vc animated:NO completion:^{
    [vc present];
}];
代码说明:
首先,在 ModalController.m 中,找到 viewDidLoad 方法加入:
self.view.backgroundColor = [UIColor clearColor];这是让背景一开始时透明,不然在呈现动画之前会出现一个短暂的白屏(零点几秒,不注意看不见)。
然后是实现 present 方法:
-(void)present{
    //1
    CGFloat originY = self.contentViewCenterY.constant;
    //2
    CGFloat viewHeight = self.view.bounds.size.height;
    // 3
    self.contentViewCenterY.constant = -(viewHeight);
    // 4
    [self.view layoutIfNeeded];
    // 5
    [UIView animateWithDuration:0.5 animations:^{
        // 将背景设置为半透明
        self.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
        // 再将 contentView 移入视图
        self.contentViewCenterY.constant = originY;
        [self.view layoutIfNeeded];
    }];
}这个方法实现呈现动画。代码解释如下:
然后实现解散动画:
-(void)dismiss{
    // 1
    CGFloat viewHeight = self.view.bounds.size.height;
    // 2
   [UIView animateWithDuration:0.5 animations:^{
       self.contentViewCenterY.constant = -(viewHeight);
       [self.view layoutIfNeeded];
   } completion:^(BOOL finished) {
       [self dismissViewControllerAnimated:NO completion:nil];
   }];
}解散动画很简单:
然后在关闭按钮或者背景 View 被触摸时调用 dismiss 播放解散动画:
- (IBAction)touched:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}标签:位置 保存 ddc add 部分 const function animation origin
原文地址:http://blog.csdn.net/kmyhy/article/details/53322669