2014-09-26 3 views
-1

Я начал разбираться с UIProgessbar, а затем у меня возникли проблемы с этим, не обновляя представление.Панель IOS UIProgressView не обновляется, может ли кто-нибудь сказать почему?

Вот мой код в виду сделал груз:

progressViewBorder = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 
                   cameraBarOverlay.frame.size.height + cameraBarOverlay.frame.origin.y, 
                   self.view.frame.size.width, 
                   10.0f)]; 

[progressViewBorder setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"progress_bg"]]]; 

progressView = [[UIProgressView alloc] init]; 
CGAffineTransform transform = CGAffineTransformMakeScale(1.0f, 5.0f); 
progressView.transform = transform; 
[progressView setFrame: CGRectMake(0.0f,5.0f,progressViewBorder.frame.size.width,1.0f)]; 
[progressView setProgressTintColor:[UIColor whiteColor]]; 
[progressView setUserInteractionEnabled:NO]; 
[progressView setProgress: 0.0f]; 
[progressView setProgressViewStyle:UIProgressViewStyleBar]; 
[progressView setTrackTintColor:[UIColor whiteColor]]; 
[progressViewBorder setHidden:YES]; 
[progressViewBorder addSubview:progressView]; 
[self.view addSubview:progressViewBorder]; 

Вот мой код обновления:

- (void)startMovieRecording:(id)sender { 
[[self recordButton] setEnabled:NO]; 
CMTime maxDuration = CMTimeMakeWithSeconds(15, 50); 
[[self movieFileOutput] setMaxRecordedDuration:maxDuration]; 

dispatch_async([self sessionQueue], ^{ 
    if (![[self movieFileOutput] isRecording]) { 

     [self setLockInterfaceRotation:YES]; 

     if ([[UIDevice currentDevice] isMultitaskingSupported]) { 
      [self setBackgroundRecordingID:[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil]]; 
     } 

     // Update the orientation on the movie file output video connection before starting recording. 
     [[[self movieFileOutput] connectionWithMediaType:AVMediaTypeVideo] setVideoOrientation:[[(AVCaptureVideoPreviewLayer *)[self previewLayer] connection] videoOrientation]]; 

     // Turning OFF flash for video recording 
     [FTCamViewController setFlashMode:AVCaptureFlashModeOff forDevice:[[self videoDeviceInput] device]]; 
     [toggleFlash setImage:[UIImage imageNamed:[flashImages objectAtIndex:2]] forState:UIControlStateNormal]; 
     currentFlashMode = [flashImages objectAtIndex:2]; 

     // Start recording to a temporary file. 
     NSString *outputFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[@"movie" stringByAppendingPathExtension:@"mov"]]; 
     [[self movieFileOutput] startRecordingToOutputFileURL:[NSURL fileURLWithPath:outputFilePath] recordingDelegate:self]; 

     while ([[self movieFileOutput] isRecording]) { 
      double duration = CMTimeGetSeconds([[self movieFileOutput] recordedDuration]); 
      double time = CMTimeGetSeconds([[self movieFileOutput] maxRecordedDuration]); 
      CGFloat progress = (CGFloat) (duration/time); 

      dispatch_async(dispatch_get_main_queue(), ^{ 
       [progressView setProgress:progress animated:YES]; 
      }); 
     } 

    } else { 
     [[self movieFileOutput] stopRecording]; 
    } 
}); 

}

Может кто-нибудь сказать, почему это не будет обновлять?

+2

Это не обновление, потому что вы блокируете поток пользовательского интерфейса с помощью цикла 'while'. – rmaddy

+0

Я обновил свой код, чтобы узнать, помогает ли он, я не уверен, если это проблема. Когда я инициализирую UIProgressView в ViewDidLoad, он не обновляется должным образом, вместо этого он занимает 50% от ширины, которая занимает 100%. Это заставляет меня думать, что происходит что-то еще, так как я пытаюсь жестко кодировать 50% только для тестирования. – SuperKevin

ответ

1

Ну это очень плохо, но оказывается, что я имел цвет оттенка и цвет оттенка выполнения, установленный на тот же .. whiteColor. Это заставило дисплей действовать очень странно.

Вот что решило это для меня.

[self.progressView setProgressTintColor:[UIColor whiteColor]]; 
[self.progressView setUserInteractionEnabled:NO]; 
[self.progressView setProgressViewStyle:UIProgressViewStyleDefault]; 
[self.progressView setTrackTintColor:[UIColor clearColor]]; 

Глядя вокруг возможных решений, я обновил свое время цикла к следующему:

while ([[self movieFileOutput] isRecording]) { 
      double duration = CMTimeGetSeconds([[self movieFileOutput] recordedDuration]); 
      double time = CMTimeGetSeconds([[self movieFileOutput] maxRecordedDuration]); 
      CGFloat progress = (CGFloat) (duration/time); 

      [self performSelectorInBackground:@selector(updateProgress:) withObject:[NSNumber numberWithFloat:progress]]; 
} 

И мой селектор делает обновление.

- (void)updateProgress:(NSNumber *)progress { 
    [self.progressView setProgress:[progress floatValue] animated:YES]; 
} 
-1

Поместите свой код в отдельный метод. Вызов этого метода с

[self performSelectorOnBackgroundThread....] 

добавить метод обновления панели Progress andcfall этот метод из вашего метода в то время как по

[self performSelectorOnMainThread....] 

Клаус

+0

Почему? Использование GCD более элегантно. Это не правильный ответ. –

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

  • Нет связанных вопросов^_^