RAC 实现按钮倒计时
- (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]];
__block id 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);
}];
}