您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

動手做一個隨機點名/抽獎小程式

編輯:iOS 開發綜合

這是一個小而完整的功能:名單在標籤上快速跳動,按下按鈕就定格在某一個名字上,再按一次繼續。核心技巧只有一個——用 NSTimer 搭配 fireDate 的「假啟動」手法來控制計時器的暫停與恢復。

為什麼不直接用 invalidate?

NSTimer 一旦 invalidate 就無法復用,得重新建立。但這裡有個更漂亮的做法:先把 fireDate 設成遙遠的未來,計時器實際上等於「掛著但不觸發」;要啟動時把 fireDate 改回過去,它就會立刻開始跑。這樣不必反覆建立物件。

程式碼

#import "ViewController.h"

@interface ViewController ()
{
    NSMutableArray *nameList;
    UILabel        *label;
    NSTimer        *timer;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];

    self.view.backgroundColor = [UIColor grayColor];

    label = [[UILabel alloc] initWithFrame:CGRectMake(50, 200, 275, 50)];
    label.text = @"不會是我吧";
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:30];
    label.textColor = [UIColor orangeColor];
    label.backgroundColor = [UIColor clearColor];
    [self.view addSubview:label];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(150, 500, 100, 100);
    [self.view addSubview:button];
    [button setTitle:@"點我啊" forState:UIControlStateNormal];
    button.backgroundColor = [UIColor redColor];
    button.layer.cornerRadius = 50;
    button.layer.masksToBounds = YES;
    button.showsTouchWhenHighlighted = YES;
    button.setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button addTarget:self
               action:@selector(push:)
     forControlEvents:UIControlEventTouchUpInside];

    // 建立每秒觸發一次的計時器
    timer = [NSTimer scheduledTimerWithTimeInterval:1
                                            target:self
                                          selector:@selector(loadData)
                                          userInfo:nil
                                           repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

    // 關鍵:把首次觸發時間推到遙遠的未來,等於暫停
    timer.fireDate = [NSDate distantFuture];
}

#pragma mark - 隨機抽一個名字
- (void)loadData {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    nameList = [NSMutableArray arrayWithObjects:
        @"a", @"b", @"c", @"俊", @"d", @"紅", @"海", @"林",
        @"楊小平", @"均", @"飛", @"寬富", @"旺", @"浩",
        @"誠", @"文興", @"水", @"波", @"金奎", @"康",
        @"黔", @"意", @"龍", @"忠華", @"濤", nil];

    [userDefaults setObject:nameList forKey:@"nameList"];
    [userDefaults synchronize];

    int arcNumber = arc4random() % nameList.count;
    label.text = nameList[arcNumber];
}

#pragma mark - 開始/暫停
- (void)push:(UIButton *)sender {
    if (sender.selected != YES) {
        // 正在跳動:隱藏文字並暫停計時器
        label.textColor = [UIColor clearColor];
        [sender setTitle:@"暫停" forState:UIControlStateNormal];
        timer.fireDate = [NSDate distantPast];
        sender.selected = YES;
    } else {
        // 已定格:恢復跳動
        timer.fireDate = [NSDate distantFuture];
        label.textColor = [UIColor blackColor];
        [sender setTitle:@"點我啊" forState:UIControlStateNormal];
        sender.selected = NO;
    }
}

- (void)showAlertMessage:(NSString *)message {
    UIAlertView *alert = [[UIAlertView alloc]
        initWithTitle:@"真的是你"
              message:message
             delegate:self
    cancelButtonTitle:@"OK"
    otherButtonTitles:nil];
    [alert show];
}

@end

幾處值得修正的地方

  • 計時器間隔太長:1 秒跳一次比較像「輪播」而不是「抽獎」。抽獎的爽感來自高速跳動後突然停住,間隔設 0.05~0.1 秒會好得多。
  • 停止時沒有定格結果:按下暫停只是把文字變透明,並沒有真的「選中」一個名字。合理的做法是在停止的瞬間把 label.text 存進變數,再彈出提示或做後續處理。
  • 每格都寫入 NSUserDefaults:loadData 每次觸發都重新組一次名單並同步寫入偏好設定,I/O 開銷完全不必要。名單應該在啟動時載入一次就夠。
  • 抽過的人重複出現:註解裡留著 [nameList removeObject:label.text],那正是避免重複的正解——抽中後就移出池子,全抽完再重置。
  • UIAlertView 已被淘汰:請改用 UIAlertController。
  • 計時器與 RunLoop:scheduledTimerWithTimeInterval: 預設只加進 NSDefaultRunLoopMode,使用者拖曳滾動時計時器會暫停。若要求絕對不間斷,改用 NSRunLoopCommonModes。

可以再加的枝節

想讓它更像真正的抽獎,可以加入「抽中後的歷史紀錄」、「已抽名單灰階顯示」、「全部抽完提示重置」這幾個功能。資料層面把 nameList 拆成「待抽池」與「已抽出」兩個陣列即可,邏輯不會複雜。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved