OC 實現自下向上的彈出檢視
阿新 • • 發佈:2018-11-01
1.建立彈出檢視UpView類:
#import <UIKit/UIKit.h>
#define contentHeight 210.0f
@interface UpView : UIView
@property (nonatomic, strong)UIView *contentView;
//彈出
- (void)show;
//隱藏
- (void)dismiss;
@end
// // UpView.m // OCTools // // Created by 周 on 2018/11/1. // Copyright © 2018年 周. All rights reserved. // #import "UpView.h" @implementation UpView - (instancetype)init { if ([super init]) { [self setUpView]; } return self; } #pragma mark - 設定介面 - (void)setUpView{ self.frame = CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT - HOME_INDICATOR_HEIGHT); self.backgroundColor = RGBA(0, 0, 0, 0.4); self.userInteractionEnabled = YES; [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)]]; [self addSubview:self.contentView]; } #pragma makr - 懶載入內容檢視 - (UIView *)contentView { if (!_contentView) { _contentView = [[UIView alloc]initWithFrame:CGRectMake(0, UI_SCREEN_HEIGHT - HOME_INDICATOR_HEIGHT, UI_SCREEN_WIDTH, contentHeight)]; _contentView.backgroundColor = [UIColor whiteColor]; } return _contentView; } #pragma mark - 彈出檢視 - (void)show { [[self lastWidow] addSubview:self]; [UIView animateWithDuration:0.3 animations:^{ [self.contentView setFrame:CGRectMake(0, UI_SCREEN_HEIGHT - HOME_INDICATOR_HEIGHT - contentHeight, UI_SCREEN_WIDTH, contentHeight)]; }]; } #pragma mark - 隱藏檢視 - (void)dismiss { [UIView animateWithDuration:0.3 animations:^{ [self.contentView setFrame:CGRectMake(0, UI_SCREEN_HEIGHT - HOME_INDICATOR_HEIGHT, UI_SCREEN_WIDTH, contentHeight)]; } completion:^(BOOL finished) { [self removeFromSuperview]; }]; } #pragma mark - 獲取最上層window - (UIWindow *)lastWidow{ NSArray *windows = [UIApplication sharedApplication].windows; for (UIWindow *window in [windows reverseObjectEnumerator]) { if ([window isKindOfClass:[UIWindow class]] && CGRectEqualToRect(window.bounds, [UIScreen mainScreen].bounds)) { return window; } } return [UIApplication sharedApplication].keyWindow; } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code } */ @end
2.使用方法:
UpView *upV = [[UpView alloc]init];
[upV show];