Overview

炒下冷饭,该篇文章发表于2016-08-07,发表在博客园https://www.cnblogs.com/wangqw/p/5738777.html,现重新排版发表于此。

友情提醒

本demo仅适用于iOS8及以上系统。

使用autolayout+storyboard实现弹窗

第一步、storyboard创建界面

1、打开storyboard 拖一个UIViewcontroller出来,并与class相关联

2、拖出一个UIView作为弹窗视图的容器,容器里放置弹窗的内容,容器高度根据具体需求放置。容器放在最底部

3、放置一个UIButton在容器View的上方间距为0,并把UIButton设置为黑色(用于实现蒙版效果及点击空白处关闭弹窗)

4、约束。底部容器打left、right、bottom、height这个约束。UIButton打 left、right、top、bottom约束 如图

底部容器约束


UIButton约束

5、约束。将底部容器的bottom约束编辑修改 如图


修改容器bottom约束


修改容器bottom约束


修改容器bottom约束

6、找到底部容器的bottom约束拉线到对应的UIViewController 如图


拉线

第二步、设置蒙版及弹窗动画

1、修改UIButton的透明度并把UIViewController的View的背景色设置为透明 如图


设置透明度

//千万别设置view的alpha 设置alpha 会导致view下的所有子视图都变透明
self.view.backgroundColor = [UIColor clearColor];

//设置按钮透明度
self.dismissBtn.alpha = 0.5f;
self.dismissBtn.backgroundColor = [UIColor blackColor];

2、实现弹窗动画,在viewDidAppear中实现,这样才可以看到整个动画过程 如图


修改约束

//视图显示完 弹出弹窗
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    //更改视图 底部约束
    self.viewBottomConstraint.constant = 0;

    //执行动画
    [UIView animateWithDuration:0.25 animations:^{

        //强制更新约束
        [self.view layoutIfNeeded];
    }];
}

3、弹出模态视图 如图


模态视图

请注意看截图,该方法所在类为ViewController

#pragma mark- 按钮点击事件
- (void)popBtn:(UIButton *)btn {

    UIStoryboard * sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    QWPopupWindowVC * vc = [sb instantiateViewControllerWithIdentifier:@"QWPopupWindowVC"];
    vc.providesPresentationContextTransitionStyle = YES;
    vc.definesPresentationContext = YES;
    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    [self presentViewController:vc animated:NO completion:nil];

}

几个属性的解释

解释内容摘至博客园 返回主页不打扰是我的温柔 http://www.cnblogs.com/SenDylan/p/3953832.html

providesPresentationContextTransitionStyle

definesPresentationContext

modalPresentationStyle

部分类容读起来怪怪的,不清楚是不是翻译软件的原因。

4、关闭弹窗


关闭弹窗

演示gif

demo

demo下载