iOS引導頁的編寫

走路放慢腳步發表於2014-03-24

我們在第一次開啟App的時候,通常不是直接進入App主介面,而是會有一個能左右滑動、介紹App功能的介面。我是用NSUserDefaults + UIScrollview實現。
新建一個類,繼承UIView,假設名為Guide。在initWithFrame方法裡:

    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    UIScrollView* scrollView = [[UIScrollView alloc] initWithFrame:frame];
    scrollView.backgroundColor = [UIColor whiteColor];
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.contentSize = CGSizeMake(320*4, screenHeight);
    scrollView.pagingEnabled = YES;
    for (int i=0; i<4; i++) {
        UIImageView* imageView = [[UIImageView alloc initWithFrame:CGRectMake(i*320, 0, 320, screenHeight)];
    imageView.contentMode = UIViewContentModeScaleAspectFill;

    NSString *filePath = [[NSBundle mainBundle] pathForResource:
                          [NSString stringWithFormat:@"FileName"
                                              ofType:@"FileType"];
    imageView.image = [UIImage imageWithContentsOfFile:filePath];
    [scrollView addSubview:imageView];
    if (i == 3) {
        UIButton* start = [UIButton buttonWithType:UIButtonTypeCustom];
        start.frame = CGRectMake(0, 0, 100, 44);
        start.layer.cornerRadius = 5;
        start.layer.borderWidth = 0.5;
        [start setCenter:CGPointMake(1120, iPhone5?450:400)];
        [start setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [start addTarget:self action:@selector(closeView) forControlEvents:UIControlEventTouchUpInside];
        [start setTitle:@"Start" forState:UIControlStateNormal];
        [scrollView addSubview:start];
    }

這樣,就有了一個有4張圖片的引導頁。
怎麼去判斷是不是第一次登陸呢,需要用到NSUserDefaults類。
在didFinishLaunchingWithOptions:函式中可以這樣判斷:

NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
if([userDefaults objectForKey:@"FirstLoad"] == nil) {
    [userDefaults setBool:NO forKey:@"FirstLoad"];
    //顯示引導頁
}

相關文章