实现引导页的两种方式

来源:互联网 发布:西班牙内战 知乎 编辑:程序博客网 时间:2024/05/21 22:43
一、直接用 scrollView
#import <UIKit/UIKit.h>@interface SRNewFeaturesViewController : UIViewController#pragma mark - Properties/** Whether to hide pageControl, default is NO which means show pageControl. */@property (nonatomic, assign) BOOL hidePageControl;/** Whether to hide skip Button, default is YES which means hide skip Button. */@property (nonatomic, assign) BOOL hideSkipButton;/** Current page indicator tint color, default is [UIColor whiteColor]. */@property (nonatomic, strong) UIColor *currentPageIndicatorTintColor;/** Other page indicator tint color, default is [UIColor lightGrayColor]. */@property (nonatomic, strong) UIColor *pageIndicatorTintColor;#pragma mark - Class methods/** Only the first start app need show new features. @return YES to show, NO not to show. */+ (BOOL)sr_shouldShowNewFeature;/** Create new features view controller with images. @param imageNames The image's name array. @param rootVC     The key window's true root view controller. @return SRNewFeatureViewController */+ (instancetype)sr_newFeatureWithImageNames:(NSArray *)imageNames rootViewController:(UIViewController *)rootVC;@end

#import "SRNewFeaturesViewController.h"@interface SRNewFeaturesViewController () <UIScrollViewDelegate>@property (nonatomic, strong) UIViewController *rootVC;@property (nonatomic, strong) NSArray          *imageNames;@property (nonatomic, strong) UIPageControl    *pageControl;@property (nonatomic, strong) UIButton         *skipButton;@property (nonatomic, strong) UIButton         *customButton;@end@implementation SRNewFeaturesViewController+ (BOOL)sr_shouldShowNewFeature {        // the app version in the sandbox    NSString *lastVersion = [[NSUserDefaults standardUserDefaults] stringForKey:@"CFBundleShortVersionString"];    // the current app version    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];    if ([currentVersion isEqualToString:lastVersion]) {        return NO;    } else {        [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:@"CFBundleShortVersionString"];        [[NSUserDefaults standardUserDefaults] synchronize];        return YES;    }}+ (instancetype)sr_newFeatureWithImageNames:(NSArray *)imageNames rootViewController:(UIViewController *)rootVC {        return [[self alloc] initWithImageNames:imageNames rootViewController:rootVC];}- (instancetype)initWithImageNames:(NSArray *)imageNames rootViewController:(UIViewController *)rootVC {        if (self = [super init]) {        self.view.backgroundColor = [UIColor whiteColor];        _imageNames = imageNames;        _rootVC = rootVC;        [self setup];    }    return self;}- (void)setup {        if (self.imageNames.count > 0) {        UIScrollView *scrollView = [[UIScrollView alloc] init];        [self.view addSubview:({            [scrollView setDelegate:self];            [scrollView setBounces:YES];            [scrollView setPagingEnabled:YES];            [scrollView setShowsHorizontalScrollIndicator:NO];            [scrollView setFrame:self.view.bounds];            [scrollView setContentSize:(CGSize){self.view.frame.size.width * self.imageNames.count, 0}];             scrollView;        })];                CGFloat imageW = self.view.frame.size.width;        CGFloat imageH = self.view.frame.size.height;        for (int i = 0; i < self.imageNames.count; i++) {            [scrollView addSubview:({                UIImageView *imageView = [[UIImageView alloc] init];                [imageView setImage:[UIImage imageNamed:_imageNames[i]]];                [imageView setFrame:(CGRect){imageW * i, 0, imageW, imageH}];                if (i == self.imageNames.count - 1) {                    // Here you can add a custom Button to switch the root controller.                    // Such as                    {                        UIButton *customBtn = [[UIButton alloc] init];                        [customBtn setImage:[UIImage imageNamed:@"start_huanshi_AR_normal"]  forState:UIControlStateNormal];                        [customBtn setImage:[UIImage imageNamed:@"start_huanshi_AR_pressed"] forState:UIControlStateHighlighted];                        [customBtn sizeToFit];                        customBtn.center = CGPointMake(self.view.frame.size.width * 0.5, self.view.frame.size.height - customBtn.frame.size.height - 100);                        [customBtn addTarget:self action:@selector(tapAciton) forControlEvents:UIControlEventTouchUpInside];                        [imageView addSubview:customBtn];                        [imageView setUserInteractionEnabled:YES];                    }                                        [imageView setUserInteractionEnabled:YES];                    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAciton)];                    [imageView addGestureRecognizer:tap];                }                imageView;            })];        }                [self.view addSubview:({            _pageControl = [[UIPageControl alloc] init];            [_pageControl setNumberOfPages:self.imageNames.count];            [_pageControl setHidesForSinglePage:YES];            [_pageControl setUserInteractionEnabled:NO];            [_pageControl setCurrentPageIndicatorTintColor:[UIColor whiteColor]];            [_pageControl setPageIndicatorTintColor:[UIColor lightGrayColor]];            [_pageControl setFrame:CGRectMake(0, self.view.frame.size.height * 0.9, self.view.frame.size.width, 40)];             _pageControl;        })];                [self.view addSubview:({            CGFloat margin = 10;            _skipButton = [[UIButton alloc] init];            _skipButton.frame = CGRectMake(self.view.frame.size.width - margin - 60, self.view.frame.size.height - margin - 40, 60, 30);            _skipButton.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];            _skipButton.layer.cornerRadius = 15;            _skipButton.layer.masksToBounds = YES;            _skipButton.titleLabel.adjustsFontSizeToFitWidth = YES;            _skipButton.titleLabel.font = [UIFont systemFontOfSize:16];            _skipButton.hidden = YES;            [_skipButton setTitle:@"跳过" forState:UIControlStateNormal];            [_skipButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];            [_skipButton addTarget:self action:@selector(skipBtnAction) forControlEvents:UIControlEventTouchUpInside];             _skipButton;        })];    }}- (void)tapAciton {        [UIView transitionWithView:[UIApplication sharedApplication].keyWindow                      duration:0.75f                       options:UIViewAnimationOptionTransitionFlipFromLeft                    animations:^{                        [UIApplication sharedApplication].keyWindow.rootViewController = self.rootVC;                    }                    completion:nil];}- (void)skipBtnAction {        [self tapAciton];}#pragma mark - Setters- (void)setCurrentPageIndicatorTintColor:(UIColor *)currentPageIndicatorTintColor {        _currentPageIndicatorTintColor = currentPageIndicatorTintColor;        [_pageControl setCurrentPageIndicatorTintColor:currentPageIndicatorTintColor];}- (void)setPageIndicatorTintColor:(UIColor *)pageIndicatorTintColor {        _pageIndicatorTintColor = pageIndicatorTintColor;        [_pageControl setPageIndicatorTintColor:pageIndicatorTintColor];}- (void)setHidePageControl:(BOOL)hidePageControl {        _hidePageControl = hidePageControl;        _pageControl.hidden = hidePageControl;}- (void)setHideSkipButton:(BOOL)hideSkipButton {        _hideSkipButton = hideSkipButton;        _skipButton.hidden = hideSkipButton;}#pragma mark - UIScrollViewDelegate- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {        NSInteger page = scrollView.contentOffset.x / scrollView.bounds.size.width;    _pageControl.currentPage = page;}@end

第一种调用:

//    BOOL shouldShow = [SRNewFeaturesViewController sr_shouldShowNewFeature];//    shouldShow = YES; // Set YES for test//    //    if (shouldShow) {//        NSArray *imageNames = @[@"guide_40_1", @"guide_40_2", @"guide_40_3", @"guide_40_4"];//        SRNewFeaturesViewController *newFeaturesVC = [SRNewFeaturesViewController sr_newFeatureWithImageNames:imageNames//                                                                                           rootViewController:navc];//        newFeaturesVC.hideSkipButton = NO; // show skip Button//        self.window.rootViewController = newFeaturesVC;//    }



二、用CollectionView写

//引导页#import "guideViewController.h"#import "guideCell.h"@interface guideViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>@property (strong, nonatomic)UICollectionView * collectionView;@property (strong, nonatomic)NSArray * imageNameArray;@property (assign, nonatomic)BOOL isHiddenNextButton;@property (strong, nonatomic)UIPageControl * pageController;@end@implementation guideViewControllerstatic NSString  * guideCellId = @"guideCell";-(NSArray *)imageNameArray{    if (!_imageNameArray) {        _imageNameArray =  @[@"guide_40_1", @"guide_40_2", @"guide_40_3", @"guide_40_4"];    }    return _imageNameArray;}- (void)viewDidLoad {    [super viewDidLoad];    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:(UIStatusBarAnimationNone)];    //引导视图    [self buildGuideView];    //页数    [self buildpageControl];}#pragma mark - 加载视图- (void)buildGuideView{    UICollectionViewFlowLayout * layout =  [[UICollectionViewFlowLayout alloc]init];    layout.minimumInteritemSpacing = 0;    layout.minimumLineSpacing = 0;    layout.itemSize = self.view.frame.size;    //水平滚动    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;        _collectionView = [[UICollectionView alloc]initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:layout];    _collectionView.backgroundColor = [UIColor whiteColor];    _collectionView.delegate = self;    _collectionView.dataSource = self;    _collectionView.showsHorizontalScrollIndicator = NO;    _collectionView.showsVerticalScrollIndicator = NO;    _collectionView.pagingEnabled= YES;    _collectionView.bounces = NO;    [_collectionView registerClass:[guideCell class] forCellWithReuseIdentifier:guideCellId];    [self.view addSubview:self.collectionView];}- (void)buildpageControl{    _pageController = [[UIPageControl alloc]initWithFrame:CGRectMake(0, Screen_height - 50, Screen_width, 20)];    _pageController.numberOfPages = self.imageNameArray.count;    _pageController.currentPage = 0;    [self.view addSubview:self.pageController];}- (void)didReceiveMemoryWarning {        [super didReceiveMemoryWarning];    }#pragma mark - delegate- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{    return  self.imageNameArray.count;}-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{       guideCell *  cell = [collectionView dequeueReusableCellWithReuseIdentifier:guideCellId forIndexPath:indexPath];        cell.guideImageView.image = [UIImage imageNamed:self.imageNameArray[indexPath.row]];    if (indexPath.row!=(self.imageNameArray.count-1)) {        [cell nextButtonHidden:YES];    }       return cell;    }-(void)scrollViewDidScroll:(UIScrollView *)scrollView{    if (scrollView.contentOffset.x != Screen_width * (self.imageNameArray.count-1)&&!self.isHiddenNextButton&&scrollView.contentOffset.x > Screen_width * (self.imageNameArray.count - 2)) {         NSIndexPath * indexpath =  [NSIndexPath indexPathForItem:self.imageNameArray.count-1 inSection:0];        guideCell * cell = (guideCell *)[self.collectionView cellForItemAtIndexPath:indexpath];        [cell nextButtonHidden:YES];;        self.isHiddenNextButton = YES;            }    self.pageController.currentPage = (scrollView.contentOffset.x /Screen_width +0.5);    }-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{    if (scrollView.contentOffset.x == Screen_width * (self.imageNameArray.count-1)) {        NSIndexPath * indexpath =  [NSIndexPath indexPathForItem:self.imageNameArray.count-1 inSection:0];        guideCell * cell = (guideCell *)[self.collectionView cellForItemAtIndexPath:indexpath];        [cell nextButtonHidden:NO];        self.isHiddenNextButton = NO;    }}/*#pragma mark - Navigation// In a storyboard-based application, you will often want to do a little preparation before navigation- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {    // Get the new view controller using [segue destinationViewController].    // Pass the selected object to the new view controller.}*/@end

cell

#import <UIKit/UIKit.h>@interface guideCell : UICollectionViewCell@property (strong, nonatomic)UIImageView * guideImageView;- (void)nextButtonHidden:(BOOL)hidden;@end

#import "guideCell.h"@interface guideCell()@property (strong, nonatomic)UIButton    * nextBtn;@end@implementation guideCell- (instancetype)initWithFrame:(CGRect)frame{    self = [super initWithFrame:frame];    if (self) {        self.backgroundColor = [UIColor whiteColor];         _guideImageView = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];        self.guideImageView.contentMode = UIViewContentModeScaleAspectFill;                     [self.contentView addSubview:self.guideImageView];        [self.contentView addSubview:self.nextBtn];            }    return self;}-(UIButton *)nextBtn{    if (!_nextBtn) {        _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];        _nextBtn.frame = CGRectMake((Screen_width - 100) * 0.5, Screen_height - 110, 100, 33);        [_nextBtn setBackgroundImage:[UIImage imageNamed:@"icon_next"] forState:(UIControlStateNormal)];        [_nextBtn addTarget:self action:@selector(nextButtonClick) forControlEvents:(UIControlEventTouchUpInside)];        _nextBtn.hidden = YES;    }    return _nextBtn;}- (void)nextButtonHidden:(BOOL)hidden{    _nextBtn.hidden = hidden;}- (void)nextButtonClick{        [[NSNotificationCenter  defaultCenter]postNotificationName:GuideViewControllerDidFinish object:nil];}@end
调用:

NSString * isFristOpen = [[NSUserDefaults standardUserDefaults] objectForKey:@"isFristOpenApp"];
    isFristOpen = nil;
    if (!isFristOpen) {
          guideViewController * guideVC = [[guideViewController alloc]init];
             self.window.rootViewController = guideVC;
        [[NSUserDefaults standardUserDefaults]setObject:@"isFristOpenApp" forKey:@"isFristOpenApp"];
        
    }

appdelegate中加入通知

#pragma mark -- 首次进入,加载完引导页后调用
- (void)registNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showMainTabBarVC) name:GuideViewControllerDidFinish object:nil];
}

- (void)showMainTabBarVC{
    LoginAndRegiterVC * vc = [[LoginAndRegiterVC alloc]init];
    LoginNavigationController *navc = [[LoginNavigationController alloc]initWithRootViewController:vc];
    self.window.rootViewController = navc;
}

0 0
原创粉丝点击