2013-04-27 3 views
0

Мне нужна помощь с UIProgressView.xcode set progressView по дате окончания

Мне нужно обновить мой прогноз прогресса с текущей даты до даты окончания, которую я выбираю.

Этот метод обновляет только метку и показывает, сколько времени осталось до конца круга.

-(void)updateProgressDate { 

    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    int units = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; 
    NSDateComponents *components = [cal components:units fromDate:[NSDate date] toDate:destDate options:0]; 
    [_dateLabel setText:[NSString stringWithFormat:@"%d%c %d%c %d%c %d%c %d%c", [components month], 'm', [components day], 'd', [components hour], 'h', [components minute], 'm', [components second], 's']]; 



} 

-(void)viewDidLoad { 

destDate = [NSDate dateWithTimeIntervalSince1970:1369342800]; 
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateProgressDate) userInfo:nil repeats:YES]; 


} 

Как я могу реализовать NSDateComponents для UIProgressView?

Благодаря

Обновлено:

- (void)viewDidLoad 
{ 

    [super viewDidLoad]; 
// Do any additional setup after loading the view. 



    //1369342800 
currentDate = [NSDate date]; 
destDate = [NSDate dateWithTimeIntervalSince1970:1369342800]; 
timeRemain = [destDate timeIntervalSinceDate:currentDate]; 
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateProgressDate) userInfo:nil repeats:YES]; 



} 


-(void)updateProgressDate { 


    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    int units = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; 
    NSDateComponents *components = [cal components:units fromDate:currentDate toDate:destDate options:0]; 
    //[_dateLabel setText:[NSString stringWithFormat:@"%d%c %d%c %d%c %d%c", [components month], 'm', [components day], 'd', [components hour], 'h', [components minute], 'm']]; 
    [_dateLabel setText:[NSString stringWithFormat:@"%dm %dd %dh %dm", [components month], [components day], [components hour], [components minute]]]; 

    [_progDate setProgress:_progDate.progress = timeRemain]; // here i did += -= right now my progress bar filled but that's not right. my circle 24 day until 24 day next month 

// как я понимаю, 1% в месяц это 0,03 верно?

NSLog([NSString stringWithFormat:@"Remain time: %dm %dd %dh %dm"], timeRemain); 

} 

поэтому ярлык srill идет нормально, но индикатор выполнения всегда заполнен.

Где я ошибаюсь?

Благодаря

ответ

0

Вы должны использовать setProgress:.

UIProgessView принимает значение от 0.0 до 1.0 в качестве аргумента. вам нужно рассчитать оставшееся время, как и в процентах в 100 раз, а затем разделить его на 100.0, чтобы получить его в диапазоне от 0.0 до 1.0 и передать его setProgress:

Edit:

Вместо того, чтобы символ в качестве параметра его можно использовать как:

[_dateLabel setText:[NSString stringWithFormat:@"%dm %dd %dh %dm %ds", [components month], [components day], [components hour], [components minute], [components second]]]; 

Также вы не должны передавать строку, вам необходимо предоставить поплавок. И NSTimeInterval сам по себе плавает.

Как я уже сказал, вам нужно преобразовать время в процентах, а затем преобразовать его в указанный диапазон.

+0

Спасибо Anoop, Но проблема здесь в этой строке: [_dateLabel SetText: [NSString stringWithFormat : @ "% d% c% d% c% d% c% d% c% d% c", [месяц компонентов], 'm', [день компонента], 'd', [час компонентов], 'h ', [components minute],' m ', [components second],' s ']]; _progDate (my uiprogressview) не может принимать строки. – Anton

+0

@ Антон: проверьте обновление/Изменить –

+0

Спасибо! Я попробую ваше решение и обновит вас. – Anton

0

Так вот правильный код, по крайней мере, теперь я могу вычислить истекшее время и отправить его для просмотра прогресса:

-(void)billRangeOperations { 

    today = [NSDate date]; 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"dd"]; 
    NSString *currentDateFormated = [dateFormatter stringFromDate:today]; 
    int dateFormated = [currentDateFormated intValue]; 
    NSLog(@"Today is: %i", dateFormated); 

    //calculate how much days in current month ****************************************** 


    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    int units = NSMonthCalendarUnit | NSDayCalendarUnit; 
    NSDateComponents *comps = [[NSDateComponents alloc] init]; 
    comps = [cal components:units fromDate:today]; 
    NSRange days = [cal rangeOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:today]; 
    NSUInteger numberOfDaysInMonth = days.length; 

    NSLog(@"%i Days in current month: %i", numberOfDaysInMonth, comps.month); 

    // end calculating ****************************************************************** 

    // calculating elapsed billing range ************************************************ 

    //dateFormated = 26; //Uncomment this string to check manually, how your billing works if date will be from 25 day of month !!!!!!!!!!!!!!!!!!!!!!!! 


    if (dateFormated < 25) { 

     int remainDaysInCurrentMonth = days.length - 25; 

     NSLog(@"Days Remain to the end of month: %i", remainDaysInCurrentMonth); 

     int elapsedTime = remainDaysInCurrentMonth + dateFormated; 

     NSLog(@"Elapsed Days: %i", elapsedTime); 

     float progress = elapsedTime * 100/days.length; 

     NSLog(@"Progress Days: %f", progress); 

     float progressTimeFormated = progress/100; 

     NSLog(@"Going to ProgressView: %f", progressTimeFormated); 

     // ************************************************************* 

     [progV setProgress:progressTimeFormated animated:YES]; 

     // remain days to the end period to text string ************************************* 

     int remainDaysPeriod = 25 - dateFormated; 

     remainDays.text = [NSString stringWithFormat:@"%i", remainDaysPeriod]; 

     // ********************************************************************************** 

    } else if (dateFormated >= 25) { 

     //***** calculating days in next month ************************* 

     comps.month = comps.month+1; 
     NSRange range = [cal rangeOfUnit:NSDayCalendarUnit 
            inUnit:NSMonthCalendarUnit 
           forDate:[cal dateFromComponents:comps]]; 
     NSLog(@"%i Days in next month: %i", range.length, comps.month); 

     //************************************************************** 


     int remainDaysInCurrentMonth = range.length - 25; 


     NSLog(@"Days Remain in current month: %i", remainDaysInCurrentMonth); 

     int elapsedTime = dateFormated - 25; 

     NSLog(@"Elapsed Time: %i", elapsedTime); 

     float progress = elapsedTime * 100/range.length; 

     NSLog(@"Progress time: %f", progress); 

     float progressTimeFormated = progress/100; 

     NSLog(@"Going to ProgressView: %f", progressTimeFormated); 

     // end calculating elapsed billing range 

     [progV setProgress:progressTimeFormated animated:YES]; 

     // remain days to the end period ******************************************************** 


     int remainDaysPeriod = remainDaysInCurrentMonth+25-elapsedTime; 

     remainDays.text = [NSString stringWithFormat:@"%i", remainDaysPeriod]; 

     // ************************************************************************************** 


     NSLog(@"More than 25"); 

    } 

} 
Смежные вопросы