Что может привести к тому, что UIScrollView потеряет часть делегата scrollview? - PullRequest
2 голосов
/ 24 октября 2011

У меня есть прокрутка, которая ведет себя странно.Он прокручивается очень «нечувствительно», без ускорения и замедления, а также без отскоков.Что может быть одной из причин, по которой это происходит?

Я подозреваю, что это как-то связано с видеозаписью, которую я пытался сделать.Эта проблема возникает только после того, как я попытался снять видео с AVFoundation ...

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

    -(void)scrollViewDidScroll:(UIScrollView *)scrollView{
        //switch if reachs halfway
        CGFloat pageWidth = scrollView.frame.size.width;
        int page = floor ((scrollView.contentOffset.x - pageWidth/2) / pageWidth) +1;
        if(self.pageControl.currentPage != page){
            [self performSelector:@selector(switchingTitle)];
            NSLog(@"scroll to change view");
        }
        NSLog(@"scrollviewdidscroll.");
        self.pageControl.currentPage = page;
    }

    -(void) scrollViewWillBeginDragging:(UIScrollView *)scrollView {
        NSLog(@"scrollviewwillbegindragging");
    }

    -(void) scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
        if(decelerate == NO){
             NSLog(@"no deceleration.");
        }
        NSLog(@"scrollviewdidenddragging");
    }

    -(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
        [self.content setDecelerationRate:UIScrollViewDecelerationRateNormal];
        NSLog(@"scrollviewwillbegindecelerating %f", self.content.decelerationRate);
    }

    -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
        NSLog(@"scrollviewdidenddeceleration");
    }

Ниже показано, как распечатка выглядит, когда я выполняю перетаскивание ... при повторном перетаскивании этот шаблон будет повторяться.

    2011-10-25 13:03:45.503  scrollviewwillbegindragging
    2011-10-25 13:03:45.507  scrollviewdidscroll.
    2011-10-25 13:03:45.536  scrollviewdidscroll.
    2011-10-25 13:03:45.560  scrollviewdidscroll.
    2011-10-25 13:03:45.565  scrollviewdidscroll.
    2011-10-25 13:03:45.580  scrollviewdidenddragging
    2011-10-25 13:03:45.582  scrollviewwillbegindecelerating 0.998000

Редактировать: добавлена ​​запись видеоприведенные ниже коды ... не все здесь, но это основная часть, которая заботится о видеозаписи, которая, как я подозреваю, является причиной того, что прокрутка перестала работать правильно

-(void) startPreview {
     //preview layer
    if(previewLayer){ previewLayer = nil; }
    previewLayer =  [AVCaptureVideoPreviewLayer layerWithSession:session];  

    if( UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation]))
        self.previewLayer.orientation = [[UIDevice currentDevice] orientation];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatepreview) name:UIDeviceOrientationDidChangeNotification object:nil]; 

    self.previewLayer.frame = CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height);
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [imageView.layer addSublayer:previewLayer]; 
}


-(void) captureSession{ 
    NSLog(@"captureSession");
    videoCaptureCompleted = NO;
    if (interrupted) {
        interrupted = NO;
    }
    //capture session
    if([session isRunning]){
        [session stopRunning];
        NSLog(@"session stopRunning");
        [[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
        session =nil;
    }

    session = [[AVCaptureSession alloc]init];

    [self startPreview];
    NSLog(@"start Preview");
    //capture device
    cameraDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];  

    //capture device input
    NSError *error=nil;  
    AVCaptureDeviceInput* cameraInputTemp = [[AVCaptureDeviceInput alloc] initWithDevice:cameraDevice error:&error]; 
    self.cameraInput = [cameraInputTemp retain];
    [cameraInputTemp release];
    if(!self.cameraInput){
        NSLog(@"camera input not found");
        return;
    }

    movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];

    CMTime maxDuration = CMTimeMake(10, 1);
    movieFileOutput.maxRecordedDuration = maxDuration;
    [session setSessionPreset:AVCaptureSessionPresetMedium];

    // Add the input and output  
    [session addInput:self.cameraInput];  

    if([session canAddOutput:movieFileOutput]){
        [session addOutput:movieFileOutput];
    }else{
        NSLog(@"session refuses to add output");
    }

    [session startRunning]; 

    [self performSelector:@selector(prepareToRecording:)  withObject:[NSNumber numberWithInt:takeCount] afterDelay:5.0];
}

-(void) prepareToRecording{
        [cameraDevice unlockForConfiguration]; 
        NSError* lockingError;
        if([cameraDevice lockForConfiguration:&lockingError]){
            [cameraDevice setFocusMode:AVCaptureFocusModeAutoFocus];
        }
        while(cameraDevice.adjustingFocus){
            [self performSelector:@selector(waitForFetch)];
        } 
        if (!cameraDevice.adjustingFocus){
            [self performSelector:@selector(startVideoRecording:) withObject:takeCt afterDelay:3.0];
        }
    }
}

 -(void)startRecording{
        [[self movieFileOutput] startRecordingToOutputFileURL:URLForVideo recordingDelegate:self];
 }

-(void) stopRecording{
    videoCaptureCompleted = YES;
    while ([movieFileOutput isRecording]) {
        [self.movieFileOutput stopRecording];
        NSLog(@"movieFileOutput stopRecording");
        [self performSelector:@selector(waitForFetch)];
    }

    //unlock configuration of autofocusing only once
    [cameraDevice unlockForConfiguration];

    if(![movieFileOutput isRecording]){
        [session performSelector:@selector(stopRunning) withObject:nil afterDelay:1.0];
    }
}

-(void) captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)URLForVideo fromConnections:(NSArray *)connections{
    NSLog(@"start recording video");

}

-(void) captureOutput:(AVCaptureFileOutput*) movieFileOutput didFinishRecordingToOutputFileAtURL: (NSURL*)URLForVideo fromConnections:(NSArray*)connections error:(NSError *)error {
    NSLog(@"recorded video");
}

-(void) startVideoRecording{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
    if(!timerOn){
        timerLabel.text = @"Recording is starting!";
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:takeCt repeats:YES];
    }
}

Может быть, вам нужна помощь?1014 *

Ответы [ 2 ]

0 голосов
/ 25 октября 2011

Если вы точно перетаскиваете вид прокрутки, эти функции не будут вызываться (замедляться). DidScroll однако будет вызван. Если, однако, вы быстро нажмете-отпустите (быстрым движением), а затем прокрутите представление вызова will begin/end decelerating обычным способом. Трудно сделать фильм в симуляторе для некоторых людей. Попробуйте на устройстве.

0 голосов
/ 24 октября 2011

Возможно, вы включили / выключили определенные функции (свойства) представления прокрутки либо в InterfaceBuilder, либо программно.Чтобы настроить эти свойства объектов (настроить в соответствии с вашими потребностями):

scrollView.pagingEnabled = NO;
scrollView.bounces = YES;
scrollView.bouncesZoom = YES;

Дополнительные свойства в UIScrollView Справочных документах .Вы также можете настроить decelerationRate на то, что вам нужно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...