ReactiveCocoa 實現 按鈕倒數計時

weixin_34162695發表於2018-11-17

- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    self.title=@"一個閱讀";

    [self testOne];

}

-(void)testOne{

    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];

    [btn setTitle:@"按鈕" forState:UIControlStateNormal];

    [btn setBackgroundColor:[UIColor colorWithRed:58/255.0f green:157/255.0f blue:255/255.0f alpha:1.0f]];

    btn.frame=  CGRectMake(30,100,100,30);

    btn.titleLabel.font = [UIFont systemFontOfSize:18.0f];

    btn.layer.cornerRadius = 6;

    btn.layer.masksToBounds = YES;

    [self.view addSubview:btn];


    RACSignal* (^countBlock)(UIButton*) = ^RACSignal*(UIButton* btn){

        RACSignal* countsingal =  [[[[RACSignal interval:1

                                              onScheduler:[RACScheduler mainThreadScheduler]]

                                      startWith:[NSDatedate]]

                                     scanWithStart:@(10)reduce:^id(NSNumber*running,idnext) {

                                         NSLog(@"running = %@",running);

                                         return@(running.integerValue-1);

                                     }]takeUntilBlock:^BOOL(NSNumber*x) {

                                         returnx.integerValue<0;

                                     }];

        returncountsingal;

    };

    RACSignal* (^CountBlock)(UIButton*) = ^RACSignal*(UIButton* btn){

        RACSignal* timeSigal =  [countBlock(btn) map:^id(NSNumber* value) {

            return [NSString  stringWithFormat:@"剩餘%@",value];

        }];

        btn.enabled=NO;

        [btn setBackgroundColor:[UIColor grayColor]];

        __blockid saveSubscriber =nil;

        RACSignal*resetStringSignal =

        [RACSignal createSignal:^RACDisposable *(id<RACSubscriber>  subscriber) {

            saveSubscriber = subscriber;

            returnnil;

        }];

        [timeSigal subscribeCompleted:^{

            btn.enabled=YES;

            [btn setBackgroundColor:[UIColor colorWithRed:58/255.0f green:157/255.0f blue:255/255.0f alpha:1.0f]];

            [saveSubscriber sendNext:@"按鈕"];

            [saveSubscriber sendCompleted];

            NSLog(@"timer singal complte");

        }];

        [btnrac_liftSelector:@selector(setTitle:forState:)

                  withSignals:[RACSignalmerge:@[timeSigal,resetStringSignal]],

         [RACSignal return:@(UIControlStateNormal)], nil];

        returntimeSigal;

    };

    btn.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {

        returnCountBlock(btn);

    }];

}


5075573-759b3f30622e0e56.gif

相關文章