jjzjj

ios - 无限滚动 UIPageViewController

coder 2023-09-21 原文

我正在尝试设置一个 UIPageViewController,它可以通过 NSUrlConnection 数据拉取动态加载页面 View 来无限滚动。我从 3 个 View 开始:prev、curr、next;并在到达 pageData 数组中的第一个或最后一个 View 时加载另一个 View 。

问题是我在 viewControllerBeforeViewControllerviewControllerAfterViewController 中加载了额外的 View 。在页面之间进行单次滑动时,这些方法似乎可以调用 2-3 次。它们也可以在从未完成页面转换的半滑动期间调用。这可能意味着多个预加载开始过早完成。然后 pageViewController 以某种方式忘记了当前位置。

[self.pageViewController setViewControllers:@[[self.pageData objectAtIndex:gotoIdx]] direction:direction animated:NO completion:nil];

下面使用这一行来表示在 pageViewController 中添加了数据,并转到适当的 View 。当我开始使用它时,它不是通过滑动进入上一个/下一个 View ,而是开始跳转到看似随机的 View 。一旦我向后滑动时开始前进......

有没有更合适的地方做页面转换完成后只调用一次的预加载?而且,是否必须调用上面的行,或者是否有更可靠的方法来确保它转到正确的页面?尝试将其连接到此处感到沮丧。

 // the init line, somewhere early on.  uses Scoll style
 self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationVertical options:nil];

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    NSUInteger index = [self.pageData indexOfObject:viewController];
    if(index == 1){
        // if loading last one on start, preload one more in advance
        [self loadSecondaryCalData:-1 endView:[[self viewControllerAtIndex:index-1] retain]];  
    } else if ((index == 0) || (index == NSNotFound)) {
        return nil;
    }

    index--;
    return [self viewControllerAtIndex:index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {

    NSUInteger index = [self.pageData indexOfObject:viewController];
    if(index == [self.pageData count]-2){
        [self loadSecondaryCalData:1 endView:[[self viewControllerAtIndex:index+1] retain]];  // if last one, preload one more in advance
    } else if (index == NSNotFound) {
        return nil;
    }

    index++;
    if (index == [self.pageData count]) {
        return nil;
    }
    return [self viewControllerAtIndex:index];
}    


- (void)loadSecondaryCalData:(int)howMany endView:(CalendarViewController*)endView {
   // initiate NSURLConnection async request for view data
}

- (void)loadSecondaryCals: (NSDictionary*)data {
   // callback for async request

   // ... process view, cal

   // add new object to page data, at start or end
   if(next){
        [self.pageData addObject:cal];
        gotoIdx = [self.pageData count]-2;
        direction = UIPageViewControllerNavigationDirectionForward;
   } else {
        [self.pageData insertObject:cal atIndex:0];
        gotoIdx = 1;
        direction = UIPageViewControllerNavigationDirectionReverse;
   }

  [self.pageViewController setViewControllers:@[[self.pageData objectAtIndex:gotoIdx]] direction:direction animated:NO completion:nil];

// alternate method to above line
/*
__block CalendarPageViewViewController *blocksafeSelf = self;
__block int blocksafeGotoIdx = gotoIdx;
__block UIPageViewControllerNavigationDirection blocksafeDirection = direction;
[self.pageViewController setViewControllers:@[[self.pageData objectAtIndex:gotoIdx]] direction:direction animated:YES completion:^(BOOL finished){
    if(finished)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [blocksafeSelf.pageViewController setViewControllers:@[[blocksafeSelf.pageData objectAtIndex:blocksafeGotoIdx]] direction:blocksafeDirection animated:NO completion:nil];
        });
    }
}];
*/


}

更新:

感谢下面的快速响应,引用了一个我不知道的很棒的函数。这是 preload 方法,非常完美,只在转换完成时调用一次。这似乎大大消除了不可靠的 View 跳转和位置遗忘。谢谢@sha!

// function to detect if we've reached the first or last item in views
// detects for full completion only
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed {

    if(completed == TRUE && [previousViewControllers count] > 0 && [pageData count] > 1){
        CalendarViewController *firstCal = [pageData objectAtIndex:0];
        CalendarViewController *lastCal = [pageData objectAtIndex:([pageData count]-1)];

        CalendarViewController *prevCal = [previousViewControllers objectAtIndex:0];
        CalendarViewController *currCal = [[pageViewController viewControllers] objectAtIndex:0];

        NSLog(@"transition completed: %@ -> %@", prevCal.week_day_date, currCal.week_day_date);
        if(currCal == firstCal){
            // preload on begining
            [self loadSecondaryCalData:-1 endView:firstCal];
        } else if(currCal == lastCal){
            // preload to end
            [self loadSecondaryCalData:1 endView:lastCal];
        }
    }
}

最佳答案

我认为您需要在 pageViewController:didFinishAnimating:previousViewControllers:transitionCompleted: 处理程序中进行加载调用。当动画结束并且新的 ViewController 变为事件状态时,将调用此方法。

关于ios - 无限滚动 UIPageViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20648679/

有关ios - 无限滚动 UIPageViewController的更多相关文章

  1. ruby - 树顶语法无限循环 - 2

    我脑子里浮现出一些关于一种新编程语言的想法,所以我想我会尝试实现它。一位friend建议我尝试使用Treetop(Rubygem)来创建一个解析器。Treetop的文档很少,我以前从未做过这种事情。我的解析器表现得好像有一个无限循环,但没有堆栈跟踪;事实证明很难追踪到。有人可以指出入门级解析/AST指南的方向吗?我真的需要一些列出规则、常见用法等的东西来使用像Treetop这样的工具。我的语法分析器在GitHub上,以防有人希望帮助我改进它。class{initialize=lambda(name){receiver.name=name}greet=lambda{IO.puts("He

  2. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  3. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  4. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  5. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  6. ruby-on-rails - ruby数组奇怪的东西(无限数组) - 2

    当我写下面的代码时:x=[1,2,3]x我得到这个输出:[1,2,3,[...]][1,2,3,[...]][1,2,3,[...]]我不应该只得到[1,2,3,[1,2,3]]吗?解释是什么? 最佳答案 这没什么奇怪的。数组的第四个元素就是数组本身,所以当你求第四个元素时,你得到的是数组,当你求第四个元素的第四个元素时,你得到的是数组,当你求第四个元素时,你得到的是数组。第四个元素的第四个元素的第四个元素的元素......你得到了数组。就这么简单。唯一有点不寻常的是Array#to_s检测到这样的递归,而不是进入无限循环,而是返回

  7. ruby - 为 IO::popen 拯救 "command not found" - 2

    当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby​​1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#

  8. ruby - IO::EAGAINWaitReadable:资源暂时不可用 - 读取会阻塞 - 2

    当我尝试使用“套接字”库中的方法“read_nonblock”时出现以下错误IO::EAGAINWaitReadable:Resourcetemporarilyunavailable-readwouldblock但是当我通过终端上的IRB尝试时它工作正常如何让它读取缓冲区? 最佳答案 IgetthefollowingerrorwhenItrytousethemethod"read_nonblock"fromthe"socket"library当缓冲区中的数据未准备好时,这是预期的行为。由于异常IO::EAGAINWaitReadab

  9. ruby - 如何使用 ruby​​ fibers 避免阻塞 IO - 2

    我需要将目录中的一堆文件上传到S3。由于上传所需的90%以上的时间都花在了等待http请求完成上,所以我想以某种方式同时执行其中的几个。Fibers能帮我解决这个问题吗?它们被描述为解决此类问题的一种方法,但我想不出在http调用阻塞时我可以做任何工作的任何方法。有什么方法可以在没有线程的情况下解决这个问题? 最佳答案 我没有使用1.9中的纤程,但是1.8.6中的常规线程可以解决这个问题。尝试使用队列http://ruby-doc.org/stdlib/libdoc/thread/rdoc/classes/Queue.html查看文

  10. ruby - 如何从 ruby​​ 中的 IO 对象获取文件名 - 2

    在ruby中...我有一个由外部进程创建的IO对象,我需要从中获取文件名。然而我似乎只能得到文件描述符(3),这对我来说不是很有用。有没有办法从此对象获取文件名甚至获取文件对象?我正在从通知程序中获取IO对象。所以这也可能是获取文件路径的一种方式? 最佳答案 关于howtogetathefilenameinC也有类似的问题,我将在这里以ruby​​的方式给出这个问题的答案。在Linux中获取文件名假设io是您的IO对象。以下代码为您提供了文件名。File.readlink("/proc/self/fd/#{io.fileno}")例

随机推荐