iOS 实现类似弹出窗口


弹出视图效果
其实要实现这样的效果很简单: 
可能很多同学试过,创建一个透明并且背景为黑色的backgroundView,然后覆盖到self.view上,然后再创建一个提示视图promptView,放到backgroundView上,但是你会发现因为backgroundView设置了alpha值,所以promptView也有他父视图的alpha值,实现的效果就不是我们这样的。其实正确的思路是: 
1. 创建一个backgroundView,设置alpha为0.1,背景色为黑色,然后添加到self.view(你需要放置的位置); 
2. 创建一个promptView,里面你有想要做的任何操作,比如有文子,有加载动画等等你想要的视图,然后添加到self.view上,注意,这里的promptView和backgroundView是兄弟关系,不是父子关系; 
这样就完成了一个类似于弹出窗口。

我们可以把这个功能性的视图封装成一个view叫PromptView, 
步骤1:在他的initWithFrame方法中,写

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        _label.center = self.center;
        _label.backgroundColor = [UIColor whiteColor];
        _label.text = @"这是提示信息";
        _label.textAlignment = 1;
        self.backgroundColor = [UIColor clearColor];
        _backgroundView = [[UIView alloc] initWithFrame:self.bounds];
        _backgroundView.backgroundColor =[UIColor blackColor];
        _backgroundView.alpha = 0.1;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_backgroundView removeFromSuperview];
            [_label removeFromSuperview];
            [self removeFromSuperview];
        });
    }
    return self;
}


步骤2:写一个弹出方法-(void)showPromptViewOnView:(UIView *)view

-(void)showPromptViewOnView:(UIView *)view
{

    [view addSubview:_backgroundView];
    [view addSubview:_label];
    [UIView animateWithDuration:0.2 animations:^{
        _label.frame =CGRectMake(100, _backgroundView.center.y, 200, 40);
    }];
}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1

然后在你想要让他出现的地方创建并且调用即可

 PromptView *view = [[PromptView alloc] initWithFrame:self.view.bounds];
    [view showPromptViewOnView:self.view];
 
 
  • 1
  • 2
  • 1
  • 2
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值