以+scheduledTimerWithTimeInterval... 的方式触发的 timer,在滑动页面上的列表时, timer 会暂定回调,为什么?如何解决?

这里强调一点:在主线程中以+scheduledTimerWithTimeInterval...的方式触发的timer 默认是运行在 NSDefaultRunLoopMode 模式下的,当滑动页面上的列表时,进入了 UITrackingRunLoopMode 模式,这时候 timer 就会停止可以修改 timer 的运行模式为 NSRunLoopCommonModes,这样定时器就可以一直运行了

以下是我的笔记补充:

子线程中通过 scheduledTimerWithTimeInterval:...方法来构建NSTimer
方法内部已经创建 NSTimer 对象,并加入到 RunLoop 中,运行模式为NSDefaultRunLoopMode

由于 Mode timer 对象,所以 RunLoop 就开始监听定时器事件了,从而开始进入运行循环
这个方法
仅仅是创建 RunLoop 对象,并不会主动启动 RunLoop,需要再调用 run方法来启动

如果在主线程中通过 scheduledTimerWithTimeInterval:...方法来构建 NSTimer,就不需要主动启动 RunLoop 对象,因为主线程的 RunLoop 对象在程序运行起来就已经被启动了 //userInfo参数:用来给NSTimeruserInfo 属性赋值,userInfo 是只读的,只能在构建 NSTimer 对象时赋值

[NSTimer scheduledTimerWithTimeInterval:1.0 target:selfselector:@selector(run:) userInfo:@"ya 了 个 hoo"repeats:YES];

// scheduledTimer...方法创建出来 NSTimer 虽然已经指定了默认模式,但是【允许你修改模式】
[[NSRunLoop currentRunLoop] addTimer:timerforMode:NSRunLoopCommonModes];

// 【仅在子线程】需要手动启动 RunLoop 对象,进入运行循环[[NSRunLoop currentRunLoop] run];

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这个问题我可以帮你解答。首先需要明确一下,你是想要在iOS应用程序的首页右上角添加一个按钮,并且点击按钮后能够跳转到另一个页面,并且在跳转页面之前还需要进行倒计,是吗? 如果是这样的话,可以按照以下步骤操作: 1. 在首页的ViewController中添加一个按钮 可以使用UIButton类来创建一个按钮,然后将它添加到视图中。在创建按钮,可以设置它的位置、大小、标题等属性。例如: ``` UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; button.frame = CGRectMake(self.view.frame.size.width - 80, 20, 60, 44); [button setTitle:@"跳转" forState:UIControlStateNormal]; [self.view addSubview:button]; ``` 这段代码在视图的右上角创建一个宽60、高44的按钮,并设置标题为“跳转”。 2. 实现按钮的点击事件 当用户点击按钮,需要执行一些操作,例如进行倒计并跳转到另一个页面。可以使用UIButton的addTarget:action:forControlEvents:方法来添加按钮的点击事件。例如: ``` [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; ``` 这段代码在按钮被点击执行buttonClicked:方法。 3. 实现倒计 在buttonClicked:方法中实现倒计。可以使用NSTimer类来实现倒计功能。例如: ``` - (void)buttonClicked:(UIButton *)sender { // 创建一个计器,每秒钟执行一次tick方法 self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(tick:) userInfo:nil repeats:YES]; } - (void)tick:(NSTimer *)timer { // 计器每秒钟执行一次该方法,更新倒计显示 self.countdown--; [self.button setTitle:[NSString stringWithFormat:@"%ld秒后跳转", (long)self.countdown] forState:UIControlStateNormal]; if (self.countdown == 0) { // 倒计结束,跳转到另一个页面 [self.timer invalidate]; [self.navigationController pushViewController:[[SecondViewController alloc] init] animated:YES]; } } ``` 这段代码创建一个计器,每秒钟执行一次tick:方法。在tick:方法中更新倒计显示,并在倒计结束跳转到另一个页面。 需要注意的是,countdown、timer和button都需要作为实例变量或属性声明,以便在不同的方法中能够访问到它们。 希望这个答案能够解决你的问题,如果还有其他问题,可以继续提问哦!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值