• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

objective-c - 在 iOS 中触发 Touch Down 的重复事件

[复制链接]
菜鸟教程小白 发表于 2022-12-13 09:46:55 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在开发一个应用程序,我希望每隔几秒调用一次方法,同时用户将手指放在按钮上,并在释放时停止。

目前我正在触发 Touch Down 事件的 NSOperation,然后应该调用 NSTimer 以在 2 秒后触发另一个 NSOperation。

然而,只有第一个“runOperation”正在发生;计时器中的不是。

- (IBAction)buttonPressedid)sender
{
    [self doStuff];
}

- (void)runOperation {
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                            selectorselector(doStuff)
                                                                          object:nil];

    [queue addOperationperation];
    [operation release];
}

- (void)doStuff {
    /* stuff goes here */

    [self performSelectorOnMainThreadselector(setTimer) withObject:nil waitUntilDone:YES];
}

- (void)setTimer
{
    timer = [[NSTimer timerWithTimeInterval:2.f target:self selectorselector(runOperation) userInfo:nil repeats:NO] retain];
}

- (IBAction)finishTakingPicturesid)sender {
    [timer invalidate];
    timer = nil;
}



Best Answer-推荐答案


XJones(没有关系)关于计划的计时器和荒谬的间接数量是正确的。但我个人确实喜欢这种用户交互模型的 NSTimer。以下是我将如何实现它。

_buttonTimer is an instance variable,
button is an IBOutlet to the button in question,
touchDown: is connected to the button's TouchDown event.

将按钮添加为 socket 无需使用 BOOL 来跟踪按钮状态,因为按钮知道它的状态。

然后将这些方法添加到您的 UIViewController 子类中。

-(void)helloMe{
    if (self.button.state == UIControlStateNormal){ 
        [_buttonTimer invalidate];
        _buttonTimer = nil
    }
    else {
        NSLog(@"Hello me");
        // Do stuff here
    }
}

- (IBAction)touchDownid)sender {
    _buttonTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selectorselector(helloMe) userInfo:nil repeats:YES];
    [_buttonTimer fire]; // If desired
}

现在运行,您将在按下按钮时在控制台中看到“Hello me”,每两秒一次,直到您松开按钮。

关于objective-c - 在 iOS 中触发 Touch Down 的重复事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8172386/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap