1. 程式人生 > >IOS 自定義從底部彈上來的View

IOS 自定義從底部彈上來的View

效果圖:


//從底部向上彈起的UIView類原始碼

#import "TFSheetView.h"

@interface TFSheetView()
{
    UIView *_contentView;
}

@end

@implementation TFSheetView

- (id)initWithFrame:(CGRect)frame
{
    if (self == [super initWithFrame:frame])
    {
        [self initContent];
    }

    return self;
}

- (void)initContent
{
    self.frame = CGRectMake(0, 0, kDEVICEWIDTH, kDEVICEHEIGHT);
    
    //alpha 0.0  白色   alpha 1 :黑色   alpha 0~1 :遮罩顏色,逐漸
    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    self.userInteractionEnabled = YES;
    [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(disMissView)]];

    if (_contentView == nil)
    {
        _contentView = [[UIView alloc]initWithFrame:CGRectMake(0, kDEVICEHEIGHT - 216, kDEVICEWIDTH, 216)];
        _contentView.backgroundColor = [UIColor redColor];
        [self addSubview:_contentView];
    }
}

- (void)loadMaskView
{
}

//展示從底部向上彈出的UIView(包含遮罩)
- (void)showInView:(UIView *)view
{
    if (!view)
    {
        return;
    }
    
    [view addSubview:self];
    [view addSubview:_contentView];
    
    [_contentView setFrame:CGRectMake(0, kDEVICEHEIGHT, kDEVICEWIDTH, 216)];
 
    [UIView animateWithDuration:0.3 animations:^{
    
         self.alpha = 1.0;

         [_contentView setFrame:CGRectMake(0, kDEVICEHEIGHT - 216, kDEVICEWIDTH, 216)];
        
    } completion:nil];
}

//移除從上向底部彈下去的UIView(包含遮罩)
- (void)disMissView
{
    [_contentView setFrame:CGRectMake(0, kDEVICEHEIGHT - 216, kDEVICEWIDTH, 216)];
    [UIView animateWithDuration:0.3f
                     animations:^{
                         
                         self.alpha = 0.0;
                         
                         [_contentView setFrame:CGRectMake(0, kDEVICEHEIGHT, kDEVICEWIDTH, 216)];
                     }
                     completion:^(BOOL finished){
                         
                          [self removeFromSuperview];
                          [_contentView removeFromSuperview];
                         
                     }];

}

@end


使用方法:

1.在一個ViewController中,初始化一個button,新增點選事件

- (void)loadBtnView
{
    UIButton *_loginButton = [[UIButton alloc]initWithFrame:CGRectMake(40, 220, kDEVICEWIDTH - 40*2, 40)];
    [_loginButton setTitle:@"載入" forState:UIControlStateNormal];
    _loginButton.backgroundColor = [UIColor grayColor];
    [_loginButton addTarget:self action:@selector(loadClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_loginButton];
}

2. 載入從底部向上彈起的UIView(如效果圖所示)
- (void)loadClicked
{
    //[_sheetView showInView:self.view];
    _tfSheetView = [[TFSheetView alloc]init];
    [_tfSheetView showInView:self.view];
}

3. 點選一下遮罩,頁面會自動下去(從上向下)